2012-01-17 146 views
0

任何大师能告诉我如何从HTML表单元素 - RADIO BUTTON和CHECK BOX获取值吗?通过Javascript访问HTML表单元素

例如,在文本框的情况下,我们可以直接通过getElementById(id).value获取值;

但如何获得组合框(下拉菜单),单选按钮和复选框的值?

谢谢。

+0

边注:几乎没有人做这种方式了,而是大多数人使用像jQuery,MooTools的,等框架,这样我们就可以只需要执行'$('#yourSelectId').val()'或'$('#yourSelectId选项:选中').val()'(jquery的例子)。 – gregmac 2012-01-17 05:42:07

+0

你可以做一些Google搜索,你会发现1000个例子。付出一点努力。 – 2012-01-17 05:50:25

回答

2

下拉显示(<select>):

var el = document.getElementById('yourSelectId'); 
var value = el.options[el.selectedIndex].value; 

如果你对待你的选择列表中的多选(组合框)中,则必须通过选项循环,如果他们选择的检查:

var el = document.getElementByid('yourSelectId'); 
var selectedValues = []; 

for (var i = 0; i < el.options.length; i++) { 
    if (el.options[i].selected) { 
     selectedValues.push(el.options[i].value); 
    } 
} 

// all selected values are now in the selectedValues array. 

单选按钮和复选框也应该有value特性,但更恰当,我想我只测试它们是否被检查:

var isChecked = document.getElementById('yourRadioOrCheckboxId').checked; 
+0

和收音机和复选框? – Acn 2012-01-17 05:32:52

+0

在答案 – 2012-01-17 05:34:05

+0

@BigFatPig:对不起,缓慢的更新。 – 2012-01-17 05:35:27

1

对于复选框,该元素有一个.checked属性:

document.getElementById('foo').checked; // true or false