Robin Michael Poothurai Robin Michael Poothurai - 7 months ago 12
Javascript Question

Add and remove item dynamically in dropdown

How can I add or remove dropdown items dynamically in jQuery? Below code is not working

$("#dropdownId").remove("<option value='12'>testing</option>");
$("#dropdownId").add("<option value='12'>testing</option>");


Can anyone suggest a way to do this?

Answer

Use a standard selector for the item you want to remove, rather than passing html markup:

$('#dropdownId option[value="12"]').remove();
// or
$('#dropdownId').remove('option[value="12"]');

(I'm assuming you don't have more than one option with the same value.)

The (approximate) opposite of .remove() is .append():

$("#dropdownId").append("<option value='12'>testing</option>");