在if语句中获取复选框值的未定义值?

时间:2017-04-10 22:22:48

标签: jquery if-statement checkbox undefined

我在jq遇到了问题!我想通过它的名字来检查复选框(它的数组)!所以一切都好,直到我使用if语句!在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);
}
}
帮助我PLZ!提前谢谢

1 个答案:

答案 0 :(得分:0)

如果没有看到完整的代码,很难知道。 确保你有一个id =“editPlz”的元素和一个name属性。 此代码有效:

$("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>