2013-11-15 32 views
0

我有一個窗體上的內聯樣式隱藏的div。我想在用戶選中「其他」複選框時顯示div。有人會看我的代碼嗎?這是行不通的。我認爲這可能是對我的標記,但如果它是JavaScript代碼,請告訴我。感謝您的任何幫助。Javascript隱藏div不想在窗體上顯示

HTML:

<div class="item"> 
    <label>How did you hear about us? <span class="req">*</span></label> 
    <br /> 
    <input type="checkbox" value="Newspaper" id="CAT_Custom_510976_0" name="CAT_Custom_510976" /> 
    Newspaper<br /> 
    <input type="checkbox" value="Direct Mail" id="CAT_Custom_510976_1" name="CAT_Custom_510976" /> 
    Direct Mail<br /> 
    <input type="checkbox" value="Radio" id="CAT_Custom_510976_2" name="CAT_Custom_510976" /> 
    Radio<br /> 
    <input type="checkbox" value="Billboard" id="CAT_Custom_510976_3" name="CAT_Custom_510976" /> 
    Billboard<br /> 
    <input type="checkbox" value="Online Search" id="CAT_Custom_510976_4" name="CAT_Custom_510976" /> 
    Online Search<br /> 
    <input type="checkbox" value="Friend" id="CAT_Custom_510976_5" name="CAT_Custom_510976" /> 
    Friend<br /> 
    <input type="checkbox" value="Social Media" id="CAT_Custom_510976_6" name="CAT_Custom_510976" /> 
    Social Media<br /> 
    <input type="checkbox" value="Other..." id="CAT_Custom_510976_7" name="CAT_Custom_510976" /> 
    Other... 
</div> 
<div style="display: none;" id="other" class="item"> 
    <label for="CAT_Custom_510977">Other:</label> 
    <br /> 
    <textarea onKeyDown="if(this.value.length&gt;=4000)this.value=this.value.substring(0,3999);" class="cat_listbox" rows="4" cols="10" id="CAT_Custom_510977" name="CAT_Custom_510977"></textarea> 
</div> 

的Javascript:

// Hide or show textarea if the other checkbox field is checked 
     var voucher = document.getElementById("CAT_Custom_510976_7"); 
     function ShowCCFields(val) {        
      if (!document.getElementById('other')) 
       return;   
      if (voucher.checked == true) 
       document.getElementById('other').style.display = 'inline'; 
      else{ 
       document.getElementById('other').style.display = 'none'; 
      } 
     } 

回答

2

你永遠不會真的調用你創建的函數。爲了讓你的函數點擊運行復選框時,你應該你的JavaScript更改爲:

var voucher = document.getElementById("CAT_Custom_510976_7"); 
    voucher.addEventListener('click', ShowCCFields); 
    function ShowCCFields(val) {        
     if (!document.getElementById('other')) 
      return;   
     if (voucher.checked == true) 
      document.getElementById('other').style.display = 'inline'; 
     else{ 
      document.getElementById('other').style.display = 'none'; 
     } 
    } 

addEventListener是什麼,然後讓函數你點擊憑證時運行。

+0

謝謝。我很感謝幫助和澄清。 – Phorden

0

你從來沒有真正分配函數被調用。

voucher.onchange = ShowCCFields; 

此外,刪除位於括號中的val,因爲您似乎沒有使用它。

+0

不應該使用'change',因爲某些瀏覽器(IE)在複選框失去焦點之前不會觸發'change'事件。如果單擊「