Jquery Javascript HTML selects
Jquery Javascript HTML selects
所以我有一个标准的选择下拉列表。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/
相关文章:
- 可以't让我的if语句处理js中的html表单输入
- 如何设置html元素填充的动画
- 使用JS如何动态更改显示的html文件中的文本背景颜色
- 如何将HTML id分配给元素,以及如何将JavaScript应用于元素
- 如何编写HTML输入的JS内联
- Dojo不解析自定义小部件的模板html中的小部件声明性
- 使用javascript将动态表从一个html页面打印到另一个html页
- 通过javascript重定向html传递php变量
- 如何使Javascript动态html表及其上的事件
- 在chrome.tabs.onCreated之后加载HTML页面
- 如何在vs2002中调试html页面
- 如何使用javascript或html下载PDF格式的填写表单
- 视频HTML没有'无法在Internet Explorer 11上工作
- HTML表单提交时未执行外部函数
- 如何将输入(type=text)从html表单传递到javascript函数
- 使用angular重定向到html页面
- 分析高度属性时出现意外值{{specs.height}}.index.html
- 在html Select中添加搜索
- 多级HTML表单
- Jquery Javascript HTML selects