1
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'.

2
  • As you wrote in the title, this is javascript, not java. Commented Sep 20, 2013 at 22:21
  • How you add those options to the drop down, or what you do with those options? Commented Sep 20, 2013 at 22:24

2 Answers 2

1

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>");
Sign up to request clarification or add additional context in comments.

1 Comment

@Duriseti - you would have to show what HTML you have and what code you tried. Also, I corrected a typo in my code.
0

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));

1 Comment

@Duriseti: Glad to hear it! (Do you know how to accept an answer, by the way?)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.