4

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>
6
  • Fyi, .attr() is a bad thing for properties. Better use .prop('selected', true_or_false) if you want to programmatically select something. The same applies for checkboxes and their checked property. But anyway, Shadow Wizard's solution is much better. Commented Oct 5, 2011 at 9:40
  • The response text is probably not equal to the value of any option. Have alert(xmlhttp.responseText) and see for yourself. Commented Oct 5, 2011 at 10:21
  • Hmm... You're right on that... For some reason my PHP is echoing back an empty string... (That's a whole other issue I guess). But even if I just hard code the number 3 into the .val('3')... Which does match one of the locations it still is a no go... This is driving me nuts and it's 3:30 am here and I'm TIRED! ;) Thanks so much! Commented Oct 5, 2011 at 10:32
  • Please use @ when replying to comment e.g. @Shadow will notify me.. I saw this just by chance now. Anyhow, .val("3") will select any option with value of 3 i.e. <option value="3">some text here</option> so post code for populate_loc_list and we might see better. Commented Oct 5, 2011 at 10:53
  • @Shadow I found my problem!! The #location_list is never actually created except dynamically... So when you go and view the code in the browser, it's not even there! The html code for it, that is... So the $("#location_list").val(xmlhttp.responseText) doesn't work because according to my jQuery code... #location_list does not exist... Hah! the entire html code that is created in the ajax call is inserted into a <span> tag... Commented Oct 5, 2011 at 11:01

5 Answers 5

11

Try this instead:

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

Setting the drop down value should do the trick.

Sign up to request clarification or add additional context in comments.

3 Comments

Nope... Tried it. Thanks though... This has been terribly frustrating. it's not crucial, but what I'm doing is dynamically building a select list after making changes the the MySQL table and then rebuilding the select list using the new data... I want the select to have the same option selected after the rebuild... Make sense? ;)
As you can see in the linked jsFiddle, it works. Before rebuilding the list store the selected value e.g. LID = $("#location_list").val(); then it should work fine.
Hmpf... I can see now that yours works in jsFiddle but for some reason mine doesn't work... Looks like I need to do some fiddling of my own... Thanks!!!
2

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

Comments

0

$("#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 ?

7 Comments

The idea might work, but your syntax is wrong and it's quite an overkill.
-1 for a) posting code that doesn't work, b) mixing jquery and direct com access (which is pretty much the reason for (a)). The correct ways to set selectedIndex are $('#location_list').prop('selectedIndex', idx); and $('#location_list')[0].selectedIndex = idx;
@Thief thanks, wasn't familiar with the .prop way - is it new in jQuery? $('#location_list')[0] is risky, when there's no such element it will crash with error.
Yes, I think it was added in 1.5. Prior to this .attr() probably worked - but accessing the field directly never did. And indeed, [0] is a bad idea - but it's still a valid way to access the underlying DOM element.
BigMike - working does not mean it's good. Why iterate over all the options and have complicated code when you can have in one line? If you can explain the benefits it would be great..
|
0

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

Comments

0

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

Comments

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.