Jquery Javascript HTML selects

Jquery Javascript HTML selects

本文关键字:selects HTML Javascript Jquery      更新时间:2023-09-26

所以我有一个标准的选择下拉列表。select中的一个选项(最后一个)我得到了一个文本字符串-var-abc。

<select id="exampleselect">
     <option>123</option>
     <option>xyz</option>
     <option>ABC</option>
</select>
var abc = "ABC";

我想做的是搜索select,找到一个与var abc匹配的选项,然后将var abc的匹配改为selected选项。

我尝试过的:

//gets all the options from the select
var selectoptions = $('#exampleselect').find('option').text(); 
//if there is a match of var abc to any of the options in the select
if (selectoptions == abc)
    {
       //work out how to get the index/eq of the matched element
       //put matched element as selected value
       $('#exampleselect').val(matchedelementindex);
    }

实时示例。

由于您不使用value属性,因此可以使用以下代码:

var myVar = 'xyz';
$('#exampleselect option').each(function(e) {
    var $this = $(this);
    if ($this.text() === myVar) {
        $this.prop('selected', true);
        return false; // stops the iteration
    }
});

您也可以使用:contains()选择器在一行中完成此操作但是如果您有一个文本为"ABC"的选项和另一个文本"ABCD"的选项,则这可能不起作用:

$('#exampleselect option:contains('+myVar+')').prop('selected', true);

尽管如此,我还是建议您在选项元素中添加一个值属性:

<select id="exampleselect">
     <option value="123">123</option>
     <option value="xyz">xyz</option>
     <option value="ABC">ABC</option>
</select>

你可以这样做:

$('#exampleselect').val(myVar);

试试这个:

var abc = "ABC";
$("#exampleselect option").each(function() {
    if ($(this).text() == abc) {
        $(this).attr("selected", true);
        return false; // exit each loop
    }
})

或者这个,尽管可读性稍差:

var abc = "ABC";
$("#exampleselect option").each(function() {
    $(this).attr("selected", $(this).text() == abc);
})

这把小提琴可能会对你有所帮助。你可以通过jQuery 支持的CSS选择器来实现这一点

var searched="abc";
$('select option['+searched+']').attr("selected","selected");

http://jsfiddle.net/7EzqU/

// iterate all select options using jquery .each method    
$('#exampleselect option').each(function () {
    // check if current option text is equal to 'ABC'
    if ($(this).text() == 'ABC') {
        // get index of option
        var index = $('#exampleselect').index($(this))
        // set selectedIndex property to change to this option
        $('#exampleselect').prop('selectedIndex', index);
    }
})

这应该可以做到:http://jsfiddle.net/xXEVw/