Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery populate select list

Tags:

jquery

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

like image 801
Nate Pet Avatar asked Apr 03 '12 17:04

Nate Pet


People also ask

How to populate select list with jQuery?

To populate select list with jQuery, use for loop along with append() and append the options to the already created select.

How do I populate a dropdown with JSON data?

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.

How do I create a dynamic selection option?

<select class="form-control"> <option selected="selected">orange</option> <option>white</option> <option>purple</option> </select> $(". js-example-tags"). select2({ tags: true });


2 Answers

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

Update

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);​
});
like image 188
Rion Williams Avatar answered Oct 19 '22 09:10

Rion Williams


You need to wait until the page has loaded before running this code. Try wrapping your code inside $(document).ready() function.

Introducing $(document).ready()

like image 41
js1568 Avatar answered Oct 19 '22 10:10

js1568