问题
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.
回答1:
I'm a little bit confused.. do you just want to update the select when the page loads? If so you can do:
CSS:
#teste {
display: none;
}
JS:
$(function(){
$('#teste').append('<option id="pera">pera</option>').val("pera").show();
});
回答2:
I think this might be what you are searching for:
Using the value:
$('[name=options]').val( 3 );//To select Blue
To reset it use:
$('[name=options]').val( '' );
Using the text:
$('[name=options] option').filter(function() {
return ($(this).text() == 'Blue'); //To select Blue
}).prop('selected', true);
Link: http://forum.jquery.com/topic/how-to-dynamically-select-option-in-dropdown-menu
回答3:
i think you want to prevent showing multiple times the teste option.
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<style>
#teste{
display: none;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$(document).click(
function(){
if(!$('#teste').is(':visible')){
$('<option/>',{
'id' : 'pera',
'html' : 'pera',
'selected' : 'selected'
}).appendTo('#teste');
$('#teste').show('slow');
}
})
});
</script>
</head>
<body>
<select id="teste">
<option value="banana">banana</option>
<option value="laranja">laranja</option>
</select>
</body>
来源:https://stackoverflow.com/questions/20576346/how-to-update-select-options-before-showing-them-in-jquery