0

I have some Select elements being populated with updated options on an interval. I'd like to access the new options programmatically to check whether a select contains an option with a certain value.

I've tried this snippet:

var exists = false;
$('#select-box option').each(function(){
    if (this.value == 'bar') {
        exists = true;
        return false;
    }
});

(From Check if value is in select list with JQuery)

But the options that this is exposing are only the placeholder options defined in the html. How can I access the options that were created by pushing new html to the element?

The selects are just defined as

<select id=select-box><option>Placeholder</option></select>.  

To update them, I'm passing several conjoined

<option>text</option> 

tags to $("#select-box").html().

user3896248
  • 347
  • 1
  • 5
  • 16

2 Answers2

0

Here is an example of creating option dynamically and function to check if there's existing option with specific value:

var index = 1;
$('#add').click(function(event) {
    var val = index++;
    var option = $('<option value="' + val + '">' + val + '</option>');
    $('#select-box').append(option);
})
$('#check').click(function(event) {

    var val = $('#value').val();
    if (val)
        if ($('#select-box option[value="' + val + '"]').length)
            $('#result').text('exist');
        else
            $('#result').text('not exist');
    else
        $('#result').text('please enter a value to check');
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id=select-box>
</select>
<br />
<button id="add">Add</button>
<br />
<input id="value" type="number" value="1" />
<button id="check">Check</button>
<br />
<br />
<span id="result">click the Check button to check</span>
Terry Wei
  • 1,521
  • 8
  • 16
0

A simple example code:

$('#addOption').click(function() {
  $('#select-box').append('<option>new</option>');
  $('#select-box').append('<option>another new</option>');

  $('#result').append('<p>Dynamic options added</p>');
  $('#result').append('<p>Accessing all options:</p>');

  $('#select-box option').each(function() {
    $('#result').append('<li>' + this.value + '</li>');
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select-box">
  <option>text</option>
</select>

<button id="addOption">
Add options
</button>

<div id="result">

</div>
Harry
  • 678
  • 10
  • 26