添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I have a program that has a drop-down menu for selecting from a list of countries. Within this list, I have selected N "important" countries that will appear at the top of the list, followed by a listing of all countries, including the countries that appeared in the "important" country part of the list.

For example:

<select id="id-search-country" name="country"> 
<option value="----">All countries
<option value="AR,,">Argentina       # you can see that this is repeated
<option value="AU,,">Australia
<option value="BR,,">Brazil
<option value="CA,,">Canada
<option value="----">----
<option value="----">All countries
<option value="AF,,">Afghanistan
<option value="AL,,">Albania
<option value="DZ,,">Algeria
<option value="AS,,">American Samoa
<option value="AR,,">Argentina        # repeated here

When I try to set the value of the users current country by using $(#id-search-country).val(current_country_value), JQuery will select the last item in the list as opposed to selecting the value at the top of the list. I would prefer it to select the country value that appears at the top of the list if it appears there.

Does anyone know how I could configure JQuery to set the current country option to the "important" country (if the current_country_value is in that part of the list), and to only select the country from the remainder of the list if it has not appeared in the "important" part?

Kind Regards

I'm gonna go with DOM parsing (selector) to find the first one, and add an attr('selected') – jcolebrand Dec 16, 2010 at 2:02 Hi gov, can you clarify? How would I updated the selected value? Isn't that what I am already doing with $(#id-search-country).val(current_country_value) – Alexander Marquardt Dec 16, 2010 at 2:08 Yes, it makes a difference for the following reason. The majority of users on my website are from a select group of countries. It is most likely that people will search within these countries. If someone searches in Spain (in my short list), and then wishes to search for people in Argentina (in my short list), they might not want to scroll through over 100 entries to find Argentina if the currently selected/searched value is now the Spain that is in the long list and is somewhere near the middle/bottom of the list, very far away from Argentina. – Alexander Marquardt Dec 16, 2010 at 2:25

Edit: After Reigel and I one-upped each other in the comments, it can be achieved with one line of jQuery:

$("#id-search-country option[value=" + current_country_value + "]:first")[0].selected = true;
                var firstCountry = $("#id-search-country option[value=" + current_country_value + "]:first"); and then next would be $("#id-search-country option")[firstCountry].selected = true;
– Reigel Gallarde
                Dec 16, 2010 at 2:19
                @Alexander, in that case try adding :first to the end of the first selector, as I've now updated in my answer. @Reigel, firstCountry is a jQuery object, not an index... you can't do $("#id-search-country option")[firstCountry]
– David Tang
                Dec 16, 2010 at 2:23
                @box9 sorry, I forgot to write in the index() at the end. should be var firstCountry = $("#id-search-country option[value=" + current_country_value + "]:first").index(); and then $("#id-search-country option")[firstCountry].selected = true;.... that would be equal to your 3 lines of codes. :D
– Reigel Gallarde
                Dec 16, 2010 at 2:35
                @Reigel... Ah thanks for that idea... the whole thing should actually be one line of code... $("#id-search-country option[value=" + current_country_value + "]:first")[0].selected = true; ;)
– David Tang
                Dec 16, 2010 at 2:40
                PS: The "first" appears to not be necessary ... I had an error in my code that caused my previous confusion.
– Alexander Marquardt
                Dec 16, 2010 at 3:21
$("select").change(function(){
    $("option[value='" + $(this).val() + "']:first").attr("selected","selected");

Basically, for this I use the attribute selector and look for the last element with the value that has just been selected. For duplicates, this will be the one at the top and for single ones, it'll be itself. Then set the selected attribute to tell the browser which should be selected.

Example: http://jsfiddle.net/jonathon/7hgjR/

I think I have an answer. It might be able to be slimmed down a bit, but with a few workarounds, here's what I got:

var options = $.makeArray($('option').each(function(){ return $(this).val()}));
var o = new Array();
for(x in options){
    o.push(options[x].value);
var x = o.indexOf('AR,,');
$('#id-search-country option').eq(x).attr('selected', 'selected');

I made the options into an array, then pushed the values to a new array (options.indexOf('AR,,') doesn't work for some reason); then selected the option based on its index, so that the first will be selected.

See it in action

You could try to remove the 'important' countries from the bottom section of the list (the full list), before selecting the country. Then add them back in the correct spots.

The selected item should remain the same.

The accepted solution given above works great if the selected value is in the list, but if it is not found it causes an error in google crome that results in the drop-down menu being completely blanked out. The fix is the following:

first_selector = $("#id-search-country option[value=" + current_country_value +  "]:first"); 
if (first_selector.length) { // check that the selector was found 
    first_selector[0].selected = true; 
} else { 
    $("#id-search-country").val(current_country_value);  // fallback to default JQuery method
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.