Monday, October 29, 2018

javascript - How do you remove all the options of a select box and then add one option and select it with jQuery?



Using core jQuery, how do you remove all the options of a select box, then add one option and select it?



My select box is the following.






EDIT: The following code was helpful with chaining. However, (in Internet Explorer) .val('whatever') did not select the option that was added. (I did use the same 'value' in both .append and .val.)




$('#mySelect').find('option').remove().end()
.append('').val('whatever');


EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons. .focus() was closer, but the option did not appear selected like it does with .selected= "true". Nothing is wrong with my existing code - I am just trying to learn jQuery.



var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");

mySelect.options[0].selected="true";


EDIT: selected answer was close to what I needed. This worked for me:



$('#mySelect').children().remove().end()
.append('') ;


But both answers led me to my final solution..



Answer



$('#mySelect')
.find('option')
.remove()
.end()
.append('')
.val('whatever')
;

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...