how can i uniquely add options to select using jquery

html-select, jquery

Solution

if (!$("#combobox option[value='Apple']").length)
    // Add it

Making it reusable can be:

if (!$("#combobox option[value='" + value + "']").length)
    // Add it

Live DEMO

case insensitive:

var isExist = !$('#combobox option').filter(function() {
    return $(this).attr('value').toLowerCase() === value.toLowerCase();
}).length;​

Full code:(of the demo)

$('#txt').change(function() {
    var value = this.value;

    var isExist = !!$('#combobox option').filter(function() {
        return $(this).attr('value').toLowerCase() === value.toLowerCase();
    }).length;

    if (!isExist) {
        console.log(this.value + ' is a new value!');
        $('<option>').val(this.value).text(this.value).appendTo($('#combobox'));
    }
});​

Live DEMO

Problem

I have a bunch of unique options in a `<select>`. I need to add a new option only if it is unique and not present in the existing options. How can I find if a given `option` already exists in a given `select` using jquery? For example: ``` <select id="combobox"> <option value="">Select one...</option> <option value="Apple">Apple</option> <option value="Banana">Banana</option> <option value="Pears">Pears</option> </select> ``` - New valid option: Pear - New invalid option: Apple

Original source

Related problems