2011-12-16 31 views
3

我正在填寫表格並希望有一個複選框,如果選中了更多表格,這不是問題,但是當表格出現時我想驗證它們,需要class=""要如何設置?驗證動態補充表格

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
    <head> 
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
    <title>Show div on check for checkbox</title> 
    <script type="text/javascript" src="jquery.js"></script> 
    </head> 

    <body> 
    <form> 
     Check me <input name="checkbox" type="checkbox" id="checkbox" onclick="$(this).is(':checked') && $('#checked').slideDown('slow')|| $('#checked').slideUp('slow');" /> 

     <p id="checked" style="display: none; margin: 10px; height: 100px; background-color: #f5f5f5; padding: 10px" > 
     <label for="form">input?</label>   
     <input class="" type="text" name="form" id="form"> 
     </p> 

     <script> 
     $("input.checkbox").click(function() { 
      if ($(this).is(":checked")) { 
      $("input.form").addClass("required"); 
      Else 
      $("input.form").removeClass("required"); 
      } 
     }); 
     </script>  
    </form> 
    </body> 
</html> 

這是我的代碼,似乎沒有工作,當我檢查源代碼之前和之後其相同。

回答

0
$(document).ready(function(){ 
    $('input[type="checkbox"]').change(function(){ 
     if ($(this).is(':checked')) { 
      $('#form').addClass('required'); 
     } else { 
      $('#form').removeClass('required'); 
     } 
    }); 
}); 
0

您的代碼有效。 jQuery不會直接影響源代碼,而只會影響當前的文檔對象模型(DOM)。如果您仍然無法得到它的工作,嘗試改變你的

<script type="text/javascript" src="jquery.js"></script>

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

此外,保持$(document).ready(function(){});函數內部jQuery腳本標籤。

0

「更多表格」我想你是指新的<input>字段,而不是新的<form> s。 你的選擇器input.form匹配類「form」的輸入元素。這是你想要的嗎?

如何以及何時擴展表單?在那個時候添加「必需」類會更好。

如果您正在尋找一種方法來設置複選框被選中時某些元素的類,請嘗試這樣;

$(document).ready(function() { 
    // Bind change event to all checkboxes 
    $('input[type="checkbox"]').change(function() { 
     // Set class "required" on all input elements 
     $("input").toggleClass("required", this.checked); 
    }); 
}); 

UPDATE

我在你的代碼定睛一看,取得了較好的解決方案。

創建了一個working example,我重命名了您的元素ID,並用div而不是p標記封裝了輸入字段。

還將兩個JavaScript部件串聯到一個事件處理程序中。

$('#myCheckbox').change(function() { 

    var isChecked = this.checked; 
    var $extendedForm = $('#extendedForm'); 

    if (isChecked) $extendedForm.slideDown('slow'); 
    else $extendedForm.slideUp('slow'); 

    $extendedForm.find('input').toggleClass("required", isChecked); 
}); 

這個JavaScript應該在script標籤被放置和$(document).ready(function(){ [CODE HERE] });