javascript tutorial - [Solved-5 Solutions] select box - javascript - java script - javascript array



Problem :

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

Solution 1:

select box is the following.

<Select id="mySelect" size="9" </Select>
click below button to copy the code. By JavaScript tutorial team

.val('whatever') did not select the option that was added. use the same 'value' in both .append and .val.

$('#mySelect').find('option').remove().end().append('<option value="whatever">text</option>').val('whatever');
click below button to copy the code. By JavaScript tutorial team

Solution 2:

var mySelect = document.getElementById('mySelect');
mySelect.options.length = 0;
mySelect.options[0] = new Option ("Foo (only choice)", "Foo");
mySelect.options[0].selected="true";
click below button to copy the code. By JavaScript tutorial team

Solution 3:

$('#mySelect')
    .find('option')
    .remove()
    .end()
    .append('<option value="whatever">text</option>')
    .val('whatever')
;
click below button to copy the code. By JavaScript tutorial team

Solution 4:

$('#mySelect')
    .empty()
    .append('<option selected="selected" value="whatever">text</option>')
;
click below button to copy the code. By JavaScript tutorial team

Solution 5:

document.getElementById("selectID").options.length = 0;
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - select box