Duriseti
Duriseti

Reputation: 11

How to add a value to the JavaScript variable?

var options = $('#mobility-table').find('select.MobilityCountry[data="'+selectionId+'"]').data('options').filter('[data="' + id + '"]');

    options.sort(function(a,b) {
        if (a.innerHTML > b.innerHTML) return 1;
        else if (a.innerHTML < b.innerHTML) return -1;
        else return 0;

The above code will give me all the list of cities upon selecting a country. I would like to add a default value 'All' at the first place in the variable 'options'. Can any one suggest me how to add this. Any help greatly appreciated. Thankyou.

Ex: options should have 'All,London,Scotland,Stanmore, Watford'.

Upvotes: 1

Views: 116

Answers (2)

Ry-
Ry-

Reputation: 224913

unshift() a new <option>:

var option = document.createElement("option");
option.value = "all";
option.appendChild(document.createTextNode("All"));
options.unshift(option);

jQuery:

options.unshift($("<option>", {text: "All", value: "all"}).get(0));

Upvotes: 0

jfriend00
jfriend00

Reputation: 707328

You can use unshift() to add an element to the beginning of the sorted array:

If you're just trying to add text to the first element, it would be like this:

options.sort(function(a,b) {
        if (a.innerHTML > b.innerHTML) return 1;
        else if (a.innerHTML < b.innerHTML) return -1;
        else return 0;
}
options.unshift("All");

If you want to add an option element to the array, it would be like this:

var item = document.createElement("option");
item.value = "all";
item.innerHTML = "All";
options.unshift(item);

It isn't clear to me whether you're also trying to change your HTML. If so, then please show what your HTML looks like so we can advise how to add that element to the DOM. It's not clear to me what HTML item is the select item.

In jQuery, you could add the option to be the first item in the drop-down like this

// you have to fill in the appropriate selector for your select object
$("#selector for select object").prepend("<option value='all'>All</option>");

Upvotes: 1

Related Questions