JQuery 按值选择选项元素

我有一个由 span 元素包装的 select 元素。我不被允许使用选择的 id,但是我被允许使用 span id。 我正在尝试编写一个 javascript/jquery 函数,其中的输入是数字 i,这是 select 选项的值之一。该函数将相关选项转换为选定的。

<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>

我写了一些东西如下(这并不完全工作,这就是为什么我张贴这个问题) :

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');


}

谢谢!

233434 次浏览

Just wrap your option in $(option) to make it act the way you want it to. You can also make the code shorter by doing

$('#span_id > select > option[value="input your i here"]').attr("selected", "selected")
options = $("#span_id>select>option[value='"+i+"']");
option = options.text();
alert(option);

here is the fiddle http://jsfiddle.net/hRFYF/

Here's the simplest solution with a clear selector:

function select_option(i) {
return $('span#span_id select option[value="' + i + '"]').html();
}
function select_option(index)
{
var optwewant;
for (opts in $('#span_id').children('select'))
{
if (opts.value() = index)
{
optwewant = opts;
break;
}
}
alert (optwewant);
}

To get the value just use this:

<select id ="ari_select" onchange = "getvalue()">
<option value = "1"></option>
<option value = "2"></option>
<option value = "3"></option>
<option value = "4"></option>
</select>


<script>
function getvalue()
{
alert($("#ari_select option:selected").val());
}
</script>

this will fetch the values

With jQuery > 1.6.1 should be better to use this syntax:

$('#span_id select option[value="' + some_value + '"]').prop('selected', true);

You can use .val() to select the value, like the following:

function select_option(i) {
$("#span_id select").val(i);
}

Here is a jsfiddle: https://jsfiddle.net/tweissin/uscq42xh/8/

$("#h273yrjdfhgsfyiruwyiywer").children('[value="' + i + '"]').prop("selected", true);

You can change with simple javascript

document.querySelector('#h273yrjdfhgsfyiruwyiywer').value='4'
<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>