I have this in my htm file
<select id="SelItem">
</select>
Within my javascript file I have a section for jquery I have the following
var itemval= '<option value="OT">OT</option>';
$("#SelItem").html(itemval);
Wouldn't the following populate my drop down with OT? It does not populate anything in the drop down
To populate select list with jQuery, use for loop along with append() and append the options to the already created select.
Bind SELECT Element with JSON Array using JavaScript I'll first create a JSON array inside a JavaScript function and add few data to it. Next, I'll iterate (loop) through each value in the array and bind the values to the SELECT element. See how I got the selected text of the SELECT element in the above example.
<select class="form-control"> <option selected="selected">orange</option> <option>white</option> <option>purple</option> </select> $(". js-example-tags"). select2({ tags: true });
You might want to consider using append:
//Creates the item
var itemval= '<option value="OT">OT</option>';
//Appends it within your select element
$("#SelItem").append(itemval);
Example
As js1568 pointed out - the problem is most likely stemming from the page not being loaded when the JS / jQuery code is being executed. You should be able to fix this with the following:
$(document).ready(function()
{
//Creates the item
var itemval= '<option value="OT">OT</option>';
//Appends it within your select element
$("#SelItem").append(itemval);
});
You need to wait until the page has loaded before running this code. Try wrapping your code inside $(document).ready()
function.
Introducing $(document).ready()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With