in Web and Tech, Work

Dynamically modifying the option for a select element with JQuery

Echoed from: https://paulund.co.uk/add-and-remove-options-in-select-using-jquery

Found these handy guide with examples for dynamically adding or removing child elements of a dropdown select element posted by Paulund on his page.


Removing an item from a select box using jQuery

JQuery is a easy way of using JavaScript reducing the time it takes to code and reduces the amount of lines you need to code. This is a good example of this is by removing an option from a select box using jQuery. If you have a select box:


<select id="selectBox" name="selectBox">
    <option value="option1"> option1 </option>
    <option value="option2"> option2 </option>
    <option value="option3"> option3 </option>
    <option value="option4"> option4 </option>
</select>

Remove From Select Drop Down

To remove a option from here you would:


$("#selectBox option[value='option1']").remove();

Add Option To Select Drop Down

To add an option to a select box, this will add an option to the end of the option list.


$("#selectBox").append('<option value="option6">option6</option>');

Remove All Options Except The First

When you have a select box that needs to be populated using Ajax you will want to keep the first option as this is used as the empty value. This will not change with any of the data that is in the select box. When using ajax you want to remove all the other options so you can re-populate the select box with the new data. Use the following code to remove all the options in the select box except for the first option.


$('select').children('option:not(:first)').remove();

Add Options From Array

If you have an array of key value pairs which you will use to populate a select box. Use the following snippet to populate a select box with a key value pair.


$.each(selectValues, function(key, value) {
     $('#mySelect')
         .append($("<option></option>")
         .attr("value",key)
         .text(value));
});

Write a Comment

Comment