2015-06-26 27 views
0

我希望在頁面加載時存儲複選框的值及其狀態。當我提交表單時,我想檢查'check'早先的複選框是否'未選中';如果是這樣,我需要將值保存在一個字符串中,以便在查詢中用作列表。我已經嘗試了以下內容,但是我的語法有些問題。請幫忙。如何在頁面加載時存儲複選框的值和狀態

<input type="checkbox" name="Periods" value="25301601" /> 
<input type="checkbox" name="Periods" value="25301602" checked /> 

<input type="button" id="buttonStore" value="Store"> 
<input type="button" id="buttonCompare" value="Compare"> 
$(document).ready(function() { 
    $("#buttonStore").click(function() { 
     // save status and value of all the checkboxes 
     var periodCHK= []; 
     $(":checkbox").each(function(){        
      periodCHK["$(this).val()"]=($(this).is(':checked'));//does not store 
      alert($(this).is(':checked')); 
      alert($(this).val()); 
     }); 
     alert(periodCHK);//nothing 
     }); 

    $("#buttonCompare").click(function() {  
     var periodstring; 
     $(":checkbox").each(function() { 
      if (!$(this).is(':checked')) 
       //if $(":checkbox").not(':checked') 
      { 
       //if this one was checked before, grab it and make a string 
       if (periodCHK["$(this).val()"]) 
       { 
        periodstring+=["$(this).val()"] + ","; 
       } 
      } 
      alert(periodstring); // does not loop 
     }); 
    }); 
}); 

回答

1

在以下聲明中使用$(this).val()不帶引號。如果與引號一起使用,它將被視爲字符串。

periodCHK[$(this).val()] 
+0

Thanks Satpal!這給了我一個水平滾動條'alert(PeriodCHK)';'這裏是我的測試[JSFiddle](http://jsfiddle.net/kaur/zj6ac1vp/36/) – Kaur

+0

@Kaur http://jsfiddle.net/satpalsingh/9md8z6ue/1/ – Satpal

+0

酷! JSfiddle中console.log的輸出在哪裏?我讓它像這樣工作 Kaur

相關問題