Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select option elements by value

I have a select element wrapped by a span element. I am not allowed to use the select id but I am allowed to use the span id. I am trying to write a javascript/jquery function in which the input is a number i, which is one of the values of the select's options. The function will turn the relevant option to selected.

<span id="span_id">     <select id="h273yrjdfhgsfyiruwyiywer" multiple="multiple">         <option value="1">cleaning</option>         <option value="2">food-2</option>         <option value="3">toilet</option>         <option value="4">baby</option>         <option value="6">knick-knacks</option>         <option value="9">junk-2</option>         <option value="10">cosmetics</option>     </select> </span> 

I wrote something as follows (this does not completely work, which is why I am posting this question):

function select_option(i) {      options = $('#span_id').children('select').children('option');     //alert(options.length); //7     //alert(options[0]); //[object HTMLOptionElement]     //alert(options[0].val()); //not a jquery element     //alert(options[0].value); //1      //the following does not seem to work since the elements of options are DOM ones not jquery's     option = options.find("[value='" + i + "']");     //alert(option.attr("value")); //undefined     option.attr('selected', 'selected');  } 

Thanks!

like image 803
rapt Avatar asked Sep 03 '11 03:09

rapt


People also ask

How do I select a specific Dropdownlist using jQuery?

Syntax of jQuery Select Option$(“selector option: selected”); The jQuery select option is used to display selected content in the option tag. text syntax is below: var variableValue = $(“selector option: selected”).

How do I get the text value of a selected option jQuery?

$var = jQuery("#dropdownid option:selected"). val(); alert ($var); Or to get the text of the option, use text() : $var = jQuery("#dropdownid option:selected").

How can check select option value is selected or not in jQuery?

$('#mySelectBox option'). each(function() { if ($(this). isChecked()) alert('this option is selected'); else alert('this is not'); });


1 Answers

Here's the simplest solution with a clear selector:

function select_option(i) {   return $('span#span_id select option[value="' + i + '"]').html(); } 
like image 156
jonathan.cone Avatar answered Sep 21 '22 19:09

jonathan.cone