Look at this example code:
<html>
<head>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("body").on('click', "#teste",function(){
$('#teste').append('<option id="pera">pera</option>')
$('#teste').show();
});
});
</script>
</head>
<body>
<select id="teste">
<option value="banana">banana</option>
<option value="laranja">laranja</option>
</select>
</body>
My problem here is that the click event show the select box and only after it updates it with the new value ("pera"). What I need to do is first update the select with the new value and only after show it. Is there anyway to do that using jQuery? Thanks in advance, guys!
EDIT:
Ok, let me try to explain a little bit clear: Whenever you click in a select to show the options it show it automatically (it's obvious!). My problem is that I need to intercept the click event, update the select and only after it show the select. But it's showing the select (it's the default behaviour) before updating. Here is what happening:
1) Select with initial values: banana, laranja
2) User click it. What I want: Show banana, laranja and pera as options. What happens: It shows banana, laranja in the list, show it and only after update the select (If I inspect the html code with fiebug, the pera option is there!). If I click again inthe select, the pera options appears normally and as the code above says, it appends another pera option in the select that only appears in the next click and so on.
i think you want to prevent showing multiple times the teste option.
I think this might be what you are searching for:
Using the value:
To reset it use:
Using the text:
Link: http://forum.jquery.com/topic/how-to-dynamically-select-option-in-dropdown-menu
I'm a little bit confused.. do you just want to update the select when the page loads? If so you can do:
CSS:
JS: