Thursday, May 23, 2024
 Popular · Latest · Hot · Upcoming
64
rated 0 times [  69] [ 5]  / answers: 1 / hits: 24649  / 12 Years ago, wed, june 6, 2012, 12:00:00

I'm updating the selected option programmatically using jQuery, but nothing changes in the browser. (That is, the old selected option remains selected instead of switching to the newly selected option.) Suggestions?



Thanks. --Jeff



I have a simple form like this:



<form id=form1 name=form1 method= action=>
<p>Assign:
<select name=assigner id=assigner>
<option value=Sam selected=selected>Sam</option>
<option value=Harry>Harry</option>
<option value=Fred>Fred</option>
</select>
<input type=button name=button1 id=button1 value=Submit />
</p>
<p> Task A: <select name=assignment[] id=assigner>
<option value=Sam>Sam</option>
<option value=Harry selected=selected>Harry</option>
<option value=Fred>Fred</option>
</select>
</p>
<p>
Task B: <select name=assignment[] id=assigner>
<option value=Sam>Sam</option>
<option value=Harry selected=selected>Harry</option>
<option value=Fred>Fred</option>
</select>
</p>
</form></div>


and my jQuery code looks like this:



<script type=text/javascript>
jQuery(document).ready(function(){
$('[name=button1]').click(
function(){
var form = $(this).parents('form');
var assigned = form.find(':selected').first().val();
form.find(':selected').each(function(index){
$(this).val( assigned ).change();
});
}
);
});
</script>

More From » jquery

 Answers
6

I'm updating the selected option programmatically using jQuery




Not as far as I can see. You're re-setting the value of the selected option, but not doing anything as far as I can tell to the actual select box.



To change a select box, you need to identify it, then call val on it, not one of its option elements.



I can't make out what you want your input[name=button1] to do, but here's an example of updating a select box: Live copy | source



HTML:



<select id=theSelect>
<option value=1>One</option>
<option value=2>Two</option>
<option value=3>Three</option>
</select>
<input type=button id=theButton value=Click me>


JavaScript:



jQuery(function($) {

$(#theButton).click(function() {
$(#theSelect).val(2);
});

});





Separately, as j08691 pointed out in the comments, you can't assign the same id value (assigner) to more than one element. id values must be unique in the document. Your code doesn't show you using that id, so this may well be unrelated, but it's worth flagging up.


[#85104] Tuesday, June 5, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dantel

Total Points: 7
Total Questions: 102
Total Answers: 97

Location: Saint Lucia
Member since Sat, Jun 6, 2020
4 Years ago
;