我只想用JavaScript获取/更改CheckBox的值.并不是说我不能使用jQuery.我尝试过这样的东西,但它不起作用.
JavaScript函数
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
Run Code Online (Sandbox Code Playgroud)
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Run Code Online (Sandbox Code Playgroud)
Tim*_*own 81
onclick相反,使用将工作.从理论上讲,它可能无法捕捉通过键盘进行的更改,但是当通过键盘检查时,所有浏览器似乎都会触发事件.
您还需要将复选框传递给函数:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
Run Code Online (Sandbox Code Playgroud)
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
Run Code Online (Sandbox Code Playgroud)
Kev*_*vin 18
您需要在使用前检索复选框.
给复选框一个id属性以检索它,document.getElementById(..)然后检查其当前状态.
例如:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
Run Code Online (Sandbox Code Playgroud)
然后您的HTML将如下所示:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
Run Code Online (Sandbox Code Playgroud)
(也改变了onchange来onclick.不能在IE工作得非常好 :).
我知道这是一个非常晚的回复,但这个代码更灵活,应该帮助像我这样的后来者.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
Run Code Online (Sandbox Code Playgroud)
HTML就像是
<input type="radio" name="bob" onclick="copycheck('from','to');" />
Run Code Online (Sandbox Code Playgroud)
其中"from"和"to"是您希望复制"to"的元素"from"的相应ID.按原样,它可以在复选框之间工作,但是只要在从html事件调用发送变量时正确定义了"to"(作为要操作的复选框),就可以输入任何你想要的ID和任何你想要的条件.
请注意,正如SpYk3HH所说,默认情况下,您要使用的目标是一个数组.使用Web开发人员工具栏中的"显示元素信息"工具将帮助您找到相应复选框的完整ID.
希望这可以帮助.
我知道这是迟到的信息,但在jQuery中,使用.checked很容易!如果你的元素是这样的:
<td>
<input type="radio" name="bob" />
</td>
Run Code Online (Sandbox Code Playgroud)
您可以轻松地获取/设置检查状态:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
Run Code Online (Sandbox Code Playgroud)
秘诀是使用"[0]"数组索引标识符,它是jquery对象的ELEMENT!请享用!