javascript 如何检查复选框是否存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9002247/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to check if a checkbox exists
提问by David
The check box's exist for each row. the table is created by PHP and I need a way to check if the check box exists. when they are created they are given the ID of checkbox_(an incrementing number).
每行都存在复选框。该表是由 PHP 创建的,我需要一种方法来检查复选框是否存在。当它们被创建时,它们被赋予了 checkbox_(一个递增的数字)的 ID。
This is what I have so far, but it does not work on checking if the element exists.
到目前为止,这是我所拥有的,但它无法检查元素是否存在。
var check = true;
var todelete = "";
var counter = 0;
//check if box exisits and record id and post
while(check)
{
if ($("#Checkbox_"+counter).length > 0)
{
todelete = todelete + $("#Checkbox_"+counter).value;
counter = counter + 1;
}
else
{
check = false;
}
}
I have also tried
我也试过
if ($("Checkbox_"+counter))
if (document.getElementById("tbody").value == null)
Update:
更新:
Even with the # symbol or if i do it by javascripts element ID - when I debug the DOM, it hits the while, then the if, adds the value to todelete, adds 1 to the counter, then it goes back to the while, then hits the if
即使使用 # 符号,或者如果我通过 javascripts 元素 ID 执行此操作 - 当我调试 DOM 时,它会命中 while,然后 if,将值添加到 todelete,将 1 添加到计数器,然后返回到 while,然后点击 if
Then bounces back up to the while without even going into the if or the else???
然后反弹到 while 甚至没有进入 if 或 else ???
this I do not understand, then it just bounces up and down between the two lines and crash's the browser?
这我不明白,然后它只是在两条线之间上下反弹并使浏览器崩溃?
Update2:
更新2:
I needed to .tostring() the counter when adding it to the string for an element id. problem solved
在将计数器添加到元素 id 的字符串时,我需要 .tostring() 计数器。问题解决了
回答by sathishkumar
You can use for "checkbox exists in this case"
您可以使用“在这种情况下存在复选框”
if ($("#Checkbox_"+counter).length > 0) {
//checkbox exists
}
回答by Grim...
You can use
您可以使用
if ($("#Checkbox_"+counter).length > 0)
I'm assuming that 'Checkbox_0' is an ID, so I've added the # symbol. If it's the name of the checkbox, you can use
我假设“Checkbox_0”是一个 ID,所以我添加了 # 符号。如果是复选框的名称,则可以使用
if ($("input[name='Checkbox_"+counter+"']").length > 0);
[edit]Also, you should check to make sure you do / don't need the capital 'C'.
[编辑]此外,您应该检查以确保您需要/不需要大写字母“C”。
回答by Sudhir Bastakoti
if (($("#Checkbox_"+counter).length) > 0) {
...
//Or something more generalized
jQuery.fn.exists = function(){
return jQuery(this).length>0;
}
//then, if you have valid selector
if ($("#Checkbox_"+counter).exists()){
//do something here if our selected element exists
}
回答by Ermes Carrer
// if document.getElementById(name) do not exist
// document.getElementById(name).value generate already an error
if (document.getElementById(name) != null) {
// you code if checkbox exist
}