2017-04-10 67 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!這是愚蠢的錯誤,非常感謝。 –