JS操作Button、Select和Radio 好记性不如烂笔头,记录⼀些常⽤的操作,⽅便随时查看:
⼀、JS操作Button
Button有两种类型 :
<input type="button" id="btn01" value="按钮1"/>
<Button id="btn02">按钮2</Button>
1.JS修改按钮⽂字⽅法
2.JS控制按钮显⽰与否
3.JS控制按钮可⽤与否
⼆、JS操作Select
1、动态添加选项option
var ElementById('mySelect');    //根据id查对象,
//添加⼀个选项
obj.add(new Option("⽂本","值"));    //这个只能在IE中有效
obj.options.add(new Option("text","value")); //这个兼容IE与firefox
2、删除所有选项option
var ElementById('mySelect');
obj.options.length=0;
3、删除⼀个选项option
var ElementById('mySelect');
//index,要删除选项的序号,这⾥取当前选中选项的序号
var index=obj.selectedIndex;
ve(index);
4、获得选项option的值
var ElementById('mySelect');
var index=obj.selectedIndex; //序号,取当前选中选项的序号
var val = obj.options[index].value;
5、获得选项option的⽂本
var ElementById('mySelect');
var index=obj.selectedIndex; //序号,取当前选中选项的序号
var val = obj.options[index].text;
6、修改选项option
var ElementById('mySelect');
var index=obj.selectedIndex; //序号,取当前选中选项的序号
htmlradio设置默认的按钮
var val = obj.options[index]=new Option("新⽂本","新值");
7、删除select
var mySelect = ElementById("mySelect");
veChild(mySelect);
三、JS操作Radio
例⼦:
<input name="test" type="radio" value="0" checked="checked" />
<input name="test" type="radio" value="1" />
<input name="test" type="radio" value="2" />
1.获取选中值,三种⽅法都可以:
$('input:radio:checked').val();
$("input[type='radio']:checked").val();
$("input[name='test']:checked").val();
2.设置第⼀个Radio为选中值:
$('input:radio:first').attr('checked', 'checked'); 或者  $('input:radio:first').attr('checked', 'true');
注:attr("checked",'checked')= attr("checked", 'true')= attr("checked", true);
3.设置最后⼀个Radio为选中值:
$('input:radio:last').attr('checked', 'checked'); 或者  $('input:radio:last').attr('checked', 'true');
4.根据索引值设置任意⼀个radio为选中值:
$('input:radio').eq(索引值).attr('checked', 'true');索引值=0, 或者 $('input:radio').slice(1,2).attr('checked', 'true');
5.根据Value值设置Radio为选中值
$("input:radio[value='rd2']").attr('checked','true'); 或者 $("input[value='rd2']").attr('checked','true');
6.删除Value值为rd2的Radio
$("input:radio[value='rd2']").remove();
7.删除第⼏个Radio
$("input:radio").eq(索引值).remove();索引值=0,  如删除第3个Radio:$("input:radio").eq(2).remove();
8.遍历Radio
function Foo()
{
var selectedIndex = -1;
var form1 = ElementsByName("test");
var i = 0;
for (i=0; i&length; i++)
{
if (form1.r[i].checked)
{
selectedIndex = i;
alert("您选择项的 value 是:" + form1.r[i].value);
break;
}
}
if (selectedIndex < 0)
{
alert("您没有选择任何项");
}
}