如何使用javascript编程设置多选框元素的值(复数)? [英] How do I programatically set the values (plural) of a multi-select box element using javascript?

查看:83
本文介绍了如何使用javascript编程设置多选框元素的值(复数)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的表单:

<form action="/cgi-bin/cgi_info.py" method="POST">
  <select id="faults" class="multiselect" multiple="multiple" name="faults[]">
    <option>Big nose
    <option>Big feet
    <option>Wrinkly nose
    <option>Wrinkly feet
    <option>Spotty nose
    <option>Spotty feet
  </select>
</form>

还要选择包含文字nose的所有选项,使用span标签

And want to select, for example, all those options containing the text 'nose' using a span tag onclick event around some text.

您可以使用onclick JavaScript代码帮助我吗?

Can you help me with the onclick javascript code?

谢谢。 p>

Thanks.

推荐答案

你必须遍历< option> 元素,内容并相应地设置属性

You have to iterate over the <option> elements, check the contents and set the selected property accordingly:

var faults = document.getElementById("faults").options,
    reg = /\bnose\b/;

for (var i=0, max = faults.length; i < max; i++) {
    faults[i].selected = reg.test(faults[i].innerHTML);
} 

示例: http://jsfiddle.net/gPQ7U/

这篇关于如何使用javascript编程设置多选框元素的值(复数)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆