验证动态添加的表单

时间:2011-12-16 08:41:21

标签: jquery

我正在处理一个表单供人填写并希望有一个复选框,如果选中了更多表单,这不是问题但是当表单出现时我想验证它们需要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>

当我检查源代码之前和之后的源代码时,这是我的代码似乎不起作用。

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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>

另外,将jQuery脚本标记保留在$(document).ready(function(){});函数中。

答案 2 :(得分:0)

使用“更多表单”,我想您指的是新的<input>字段,而不是新的<form>。 您的选择器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);
    });
});

<强>更新

我仔细查看了您的代码,并提供了更好的解决方案。

创建了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] });