问题描述:

I have a situation where I need to programatically select an option within a select. I cannot seem to locate an answer and my brain is turning to mush... This is what I have been trying (and various other variations).

$("#location_list option[value='"+LID+"']").attr("selected", "selected");

Any help would be GREATLY appreciated!

Thanks!

Here is the surrounding code...

function loc_commitData(location_data, update_loc)

{

if (window.XMLHttpRequest)

{

xmlhttp = new XMLHttpRequest();

}

else

{

xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.onreadystatechange = function()

{

if (xmlhttp.readyState == 4 && xmlhttp.status == 200)

{

populate_loc_list('<?php echo $CompanyID; ?>', $("input:radio[name='locationstatus']:checked").val());

bind_events_to_location_list();

$("#location_list").val(xmlhttp.responseText);

}

}

xmlhttp.open("GET", "includes/save_location_data.php?" + location_data, true);

xmlhttp.send();

};

Here is the HTML snippet where the location_list is inserted within the span tags...

<fieldset style="margin-right: 15px;">

<legend>Locations</legend>

<span id="location_list_span"> THIS IS WHERE location_list GETS INSERTED ON THE FLY AFTER THE PAGE IS CREATED BY PHP</span>

</fieldset>

网友答案:

Try this instead:

$("#location_list").val(LID);

Setting the drop down value should do the trick.

网友答案:

When using jquery 1.9.1 and jquery mobile 1.3.0 you have to add a refresh statement:

$("#location_list").val(LID);
$("#location_list").selectmenu("refresh");

Test it on jsfiddle

网友答案:

$("#location_list").selectedIndex = index of the obj;

EDIT:

well actually I've this in one of my old script and yeah it actually works giving the right index. However Since we're speaking about canonical ways, I've crossed something like:

select.children("option").each(function () {
  if ($(this).text().match(matcher)) {
    this.selected = valid = true;
  }
});

Why should I use the parent select instead of using the options collection ?

网友答案:

After reading your comment to Shadow Wizard (which suggested the right solution) it seems like you might have one of two problems:

  1. timing problem - you have code like this:

    var LID = $("#location_list").val();   
    $.ajax(/*go get items for new  select and populate it on success*/);   
    $("#location_list").val(LID); //this will happen before the ajax return and populate the list
    
  2. you don't return the value in the new list or you try to set it's value by it's text

oh and forgot to add the solution to 1 - just select the old value in the success callback of the Ajax call after you repopulate the list

网友答案:

I used this code and it worked for me.
$("#selectID option")[index].selected = true;

相关阅读:
Top