0

I need to make selected option 17 using JQuery I can't use value, because it's always different. So is there any solution to use number of 'select' child or somthing? Thank you.

<select name="size" id="size">
    <option value="1430">17</option>
    <option value="1429">19</option>
    <option value="1428">20</option>
    <option value="1427">16</option>
    <option value="1426">15</option>
    <option value="1425">18</option>
</select>

3 Answers3

4
$('select[name="size"] option').each(function() {
   if($(this).text() == '17') {
       $(this).prop('selected', true);
   }
});
Nadh
  • 6,987
  • 2
  • 21
  • 21
3

You can use the :contains() selector:

$("#size").find("option:contains(17)").prop("selected",true);

Though that would pick up text like 1117 too. So you could use .filter() (with or with $.trim()):

$("#size option").filter(function() {
    return $.trim($(this).text()) === "17";
}).prop("selected", true);

Or a good old .each() loop will let you stop as soon as you find a matching item, so it's messier than .filter() but more efficient:

$("#size option").each(function() {
    if ($.trim($(this).text()) === "17") {
       $(this).prop("selected", true);
       return false;
    }
});
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

Jquery Makes developers life so easy :)

var setstatus=17;
 $("#size option:contains(" + setstatus + ")").attr('selected', 'selected');
Satinder singh
  • 10,100
  • 16
  • 60
  • 102