单选框和复选框

本文介绍如何使用HTML和JavaScript来创建并操作单选框和复选框,包括设置默认选项、获取选中值及动态创建表单元素等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1. 单选框

<label><input name="channel" type="radio" id="subChannel" value="子渠道" onClick="subChannelClick()"/>子渠道</label>
<label><input name="channel" type="radio" id="mainChannel" value="主渠道" style="margin-left:40px;" onClick="mainChannelClick()"/>主渠道</label>

js代码:

设置默认选择:

$('#mainChannel').attr("checked","checked");

获取选中的值

$('input:radio[name="channel"]:checked').val();

设置为不可选

$('#selectMainChannelBtn').linkbutton({disabled: false});

设置为可选

$('#selectMainChannelBtn').linkbutton({disabled: true});


使用一段时间后,我发先这个attr有bug,点的次数多了,就不响应了。解决办法:把attr换成prop就可以了

$('#mainChannel').prop("checked","checked");


2. 复选框

<td id="system"></td>

js代码:

var checkBox = document.createElement("input");
        checkBox.setAttribute("type","checkbox");
        checkBox.setAttribute("id", "id1");
        checkBox.setAttribute("name", "name1");
        checkBox.setAttribute("value", "zyyTest");
var label=document.createElement("label");
        label.appendChild(checkBox);
        label.appendChild(document.createTextNode("zyyTest"));
document.getElementById("system").appendChild(label);

//获取选择框选中的值

var str = '';
$('input:checkbox[name="name1"]:checked').each(function(){ 
str = str + $(this).val();
});

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值