2017-04-10 70 views
0

我在jq上遇到了问题!我试图通过它的名字检查复选框(它的数组)!所以一切都很好,直到我用if语句!在if语句中它的undefined!请看这里:在if语句中获取复选框值的未定义值?

$('#editSub').click(function(){ 
var $nameGiven=$('#editPlz').attr('name'); 
//here I got the values ! 
var values = new Array(); 
$.each($("input[name='status[]']:checked"), function() { 
    values.push($(this).val()); 
}); 

//this alert give forexample 102,103 
alert(values); 


if($nameGiven == 'status[]'){ 
    //but here its undefined !!!!!! whyyy ????? 
    alert(values); 
} 
} 

help me plz!在此先感谢

+0

任何机会,你可以发布的HTML代码,其中包括你的'#editSub'element和你投入在JavaScript沙盒测试吗? – Lixus

+0

[它的小提琴链接,检查这里的问题!](https://jsfiddle.net/s43k68xd/6/) –

回答

0

很难知道没有看到您的完整代码。 确保您具有id =“editPlz”和名称属性的元素。 此代码的工作:

$("document").ready(function() { 
 
    $('#editSub').click(function() { 
 
     var $nameGiven = $('#editPlz').attr('name'); 
 
     //here I got the values ! 
 
     var values = new Array(); 
 
     $.each($("input[name='status[]']:checked"), function() { 
 
      values.push($(this).val()); 
 
     }); 
 

 
     //this alert give forexample 102,103 
 
     alert(values); 
 

 
     if ($nameGiven == 'status[]') { 
 
      //but here its undefined !!!!!! whyyy ????? 
 
      alert(values); 
 
     } 
 
    }); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<!DOCTYPE html> 
 

 
<html lang="en" xmlns="http://www.w3.org/1999/xhtml"> 
 
<head> 
 
    <meta charset="utf-8" /> 
 
    <title></title> 
 
</head> 
 
<body> 
 
    <input type="checkbox" name="status[]" value="1"/> 
 
    <input type="checkbox" name="status[]" value="2"/> 
 
    <input type="checkbox" name="status[]" value="3"/> 
 
    <input type="checkbox" name="status[]" value="4"/> 
 
    <input type="checkbox" name="status[]" value="5"/> 
 
    
 
    <input type="checkbox" name="status[]" id="editPlz" /> 
 

 
    <input type="button" id="editSub" value="click"/> 
 
</body> 
 
</html>

+0

看到js小提琴链接,我把它放在评论plz,tnx。 –

+0

您没有任何带有'editPlz'ID的元素。 – Tal

+0

是的你是正确的,输入是在PHP中,而我删除editPlz ID后,我发生了这个错误,所以我删除它,并改变了一下......但我没有添加editPlz ID!这是愚蠢的错误,非常感谢。 –