jQuery按值选择选项元素


89

我有一个由span元素包裹的select元素。我不允许使用选择ID,但可以使用跨度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');

}

谢谢!

Answers:


148

这是带有清晰选择器的最简单解决方案:

function select_option(i) {
  return $('span#span_id select option[value="' + i + '"]').html();
}

32

使用jQuery> 1.6.1时,最好使用以下语法:

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

29

只需将您的选项包装在$(option)中,使其按照您希望的方式起作用。您还可以通过执行以下操作使代码更短

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


6

您可以使用.val()选择值,如下所示:

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

这是一个jsfiddle:https ://jsfiddle.net/tweissin/uscq42xh/8/


它不适用于哪个浏览器/平台?在Mac / Chrome上,它成功选择了列表中的一项,这正是原始问题所在。
汤姆(Tom)

@Llama先生,您可能误解了这个问题。@汤姆的代码没有什么问:给定值i,选择第i个optionselect。OP并未尝试过滤选项。
保罗

4

要获取值,请使用以下命令:

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

这将获取值


1
function select_option(index)
{
    var optwewant;
    for (opts in $('#span_id').children('select'))
    {
        if (opts.value() = index)
        {
            optwewant = opts;
            break;
        }
    }
    alert (optwewant);
}

谢谢!我不知道jQuery的内部实现是什么,但是其他解决方案看起来更简单。
全神贯注

如果您已经有了jQuery,那么它们会更简单,但是我认为您可能想知道一种纯js的方法。
霍根

0
$("#h273yrjdfhgsfyiruwyiywer").children('[value="' + i + '"]').prop("selected", true);
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.