2015-06-19 57 views
0

我需要保存我的頁面上覆選框的值以及狀態;所以我可以在提交時檢查複選框是否未選中,並使用comparestatus()函數的值來獲取更多邏輯。我已經試過這個,我得到的錯誤是變量periodCHK沒有定義。如何保存複選框值和狀態

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

<script type="text/javascript"> 
    $j(document).ready(function() { 
     var periodCHK; 
     $j(":checkbox").each(function() {       
      periodCHK["$j(this.id).val()"]=($j(this).is(':checked')); 
     }); 

     console.log(periodCHK); 

     function comparestatus() { 
      var periodstring; 
      if (!$j(this).is(':checked')) { 
       // if this one was checked before, grab it and make a string 
       if (window.periodCHK["$j(this.id).val()"]) 
       { 
        periodstring+=["$j(this.id).val()"] + ","; 
       } 
      } 
     } 
    }); 
</script> 
+0

您必須將periodCHK定義爲Object,'var periodCHK = {}' –

回答

1

您的periodCHK變量在您的document.ready模塊中使用var進行了(正確)聲明,因此它只存在於該函數範圍內。

if (periodCHK["$j(this.id).val()"])

(注:你可以簡單地通過訪問它,纔能有你的變量是在全球範圍內訪問(window),你要麼必須聲明它沒有var或明確其分配給但是,這通常是不好的做法。)

1

您聲明var periodCHK一個函數裏面,所以它不會成爲window的屬性。你在comparestatus裏面用window.periodCHK來叫它,它應該是periodCHK。這應該起作用,因爲功能comparestatus在同一個函數中聲明,其中periodCHK也被聲明。他們在相同的範圍內。

+0

我明白了!謝謝! – Kaur