0

I have a select Input menu that is created dynamically, This creates a row item. The user can then click the row to edit their selection. I am having a problem setting the default drop down option to a variable. I put a simplified version of my problem in a jsfiddle.

http://jsfiddle.net/SteveRobertson/cPtLj/1/

What I am trying to do in the fiddle is have the default option be option3.

I have also tried using "value" instead of "text" and doing this

   $("#selectid option[value='"+cat+"']").prop("selected", "selected");

I can not seem to get the value to set. Any help would be appreciated. Thank you.

4

3 回答 3

2
var text1 = 'your text';
$("select option").filter(function() {
    return $(this).text() == text1; 
}).prop('selected', true);

or use

<select id="selectid">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>

$(document).ready(function () {
 $("#selectid").val("option3");
});
于 2013-06-06T03:20:18.483 回答
2

Working jsFiddle Demo

Try this:

$(document).ready(function() {
    var cat = 'option3';
    $("#selectid option:contains(" + cat + ")").prop("selected", true);
});

Notes:

  • In your jsFiddle, you didn't include jQuery..
  • You were using cat in your code, as a string, not a variable.
  • In this case, I used :contains() Selector.
  • The .prop() method need boolean as its second arguments.

References:


UPDATED

This method is fair enough. It's also works for options like option11 and option111:

$(document).ready(function() {
    // your string
    var cat = 'option11';

    // get all options
    $("#selectid option")
        // remove all selected
       .prop("selected", false)

       // now filter the one you want
       .filter(function () {
           return $.trim($(this).text()) == cat;
       })
            // select it
           .prop('selected', true);

});
于 2013-06-06T03:21:44.783 回答
0

First you haven't included the jQuery library in your fiddle.

$('document').ready(function () {
    $("select#selectid").val("option3");
});

Check out this JSFiddle

于 2013-06-06T03:25:28.093 回答