user481610
user481610

Reputation: 3270

jquery not populating select

I'm using jquery and jquery mobile to simply populate a select element. Here is the js:

var SelectDropDown = $("#searchuniversity");
SelectDropDown.empty();
var NewOption = new Option("Select University" ,"");
SelectDropDown.add(NewOption);
for (var i = 0; i < ArrayUniversisities.length ; i++) 
{
        var NewOption = new Option(ArrayUniversisities[i] ,i);
        SelectDropDown.add(NewOption);
        SelectDropDown.selectedIndex = 0;
};

Here is the HTML:

<select name="searchuniversity" id="searchuniversity" required></select>

Why is this not working?

Upvotes: 1

Views: 152

Answers (2)

adamgede
adamgede

Reputation: 2152

Use 'append' instead of 'add'

var ArrayUniversisities = [ 15, 16, 17 ]; // I don't know what you had in your original array, but here's a simple example.

var SelectDropDown = $("#searchuniversity");
SelectDropDown.empty();
var NewOption = new Option("Select University" ,"");
SelectDropDown.append(NewOption); // Use append instead of add.
for (var i = 0; i < ArrayUniversisities.length ; i++) 
{
        var NewOption = new Option(ArrayUniversisities[i] ,i);
        SelectDropDown.append(NewOption); // Use append instead of add.
        SelectDropDown.selectedIndex = 0;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="searchuniversity" id="searchuniversity" required></select>

Add (http://api.jquery.com/add/) is used in a selection type of environment, like if you're looking up multiple elements, and want to add another item to that lookup.

Append (http://api.jquery.com/append/) will append the option element to the select element.

Upvotes: 1

Hanlet Esca&#241;o
Hanlet Esca&#241;o

Reputation: 17380

Use append instead of add:

var SelectDropDown = $("#searchuniversity");
SelectDropDown.empty();
var NewOption = new Option("Select University" ,"");
var ArrayUniversisities = [1, 2, 3, 4];
SelectDropDown.append(NewOption);
for (var i = 0; i < ArrayUniversisities.length ; i++) 
{
        var NewOption = new Option(ArrayUniversisities[i] ,i);
        SelectDropDown.append(NewOption);
        SelectDropDown.selectedIndex = 0;
};

http://jsfiddle.net/hescano/1oxa2q4a/

Upvotes: 1

Related Questions