4

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
brainydexter
  • 19,826
  • 28
  • 77
  • 115
  • Extension to my question: Is there a utility that can give me an intersection of these two sets ? (I know I can write it easily, but if something already exists, I'd rather reuse it). For e.g. givenOptions and newOptions. I'd like to add the intersection of these two to givenOptions. – brainydexter May 29 '12 at 11:54
  • [Watch my updated answer](http://stackoverflow.com/a/10798112/601179) to your case-insensitive request. – gdoron May 29 '12 at 12:23
  • What do you mean by 'intersection of the two options'? – David Thomas May 29 '12 at 15:49
  • @DavidThomas Existing options (givenOptions in this case: Apple, Banana, Pears). newOptions is like an array (which I get through an ajax call, for example [apple, plums]). I'd like to get the intersection of `givenOptions` and `newOptions` to find unique elements in the two set and add those to `givenOptions`. – brainydexter May 29 '12 at 16:05

4 Answers4

9
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

gdoron
  • 147,333
  • 58
  • 291
  • 367
  • How can I make this case-insensitive ? – brainydexter May 29 '12 at 12:04
  • Awesome! can you please explain what is the `!!` operator in jquery ? I couldn't understand this part: `!!$('#combobox option').filter(...` – brainydexter May 29 '12 at 12:37
  • Thanks gdoron! That was helpful. Are you aware of a a utility that can give me an intersection of these two `options` ? (I know I can write it easily, but if something already exists, I'd rather reuse it). For e.g. givenOptions from the current set of options and newOptions received as a json array. I'd like to add the intersection of these two to givenOptions. my related question: http://stackoverflow.com/questions/10796413/how-to-use-jquery-autocomplete-combobox-with-ajax-json-data – brainydexter May 29 '12 at 15:30
  • @brainydexter. There is no built in way for it. You'll need to write it yourself. It's not that hard, proximity 3-5 lines of code. – gdoron May 29 '12 at 15:41
2

I presume you want to search by value rather than by the text content. In your example, they're always the same, but possibly they won't always be...

var toAdd = 'Apricot',
    combobox = $('#combobox');

if (!combobox.find('option[value="' + toAdd + '"]').length) {
    combobox.append('<option value="' + toAdd + '">' + toAdd + '</option>');
}
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
1

Assuming that the new option-text is present in the newOption variable:

$('button').click(
    function() {
        var newOption = $('#newOptionInput').val(),
            opts = [];
        $('#combobox option').each(
            function() {
                opts.push($(this).text());
            });

        if ($.inArray(newOption, opts) == -1) {
            $('<option />')
                .val(newOption)
                .text(newOption)
                .appendTo('#combobox');
        }
    });​

JS Fiddle demo.

Edited to correct the above code (I forgot that $.inArray() returns -1, not false when a value isn't found), and use a more appropriate selector.

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
0
if ($('#combobox').find('option[value="Pear"]').length) {
  // there's pear
} else {
  // nope, no pear
}
Amadan
  • 191,408
  • 23
  • 240
  • 301