简体   繁体   English

使用jQuery验证动态创建的div

[英]Validating dynamically created div using jquery

I am adding div dynamically with having multiple input tag to a div having id="lessonDetails". 我正在将具有多个输入标签的div动态添加到具有id =“ lessonDetails”的div中。 I am trying to validate it with jquery, code is as below : 我正在尝试使用jquery对其进行验证,代码如下:

html: 的HTML:

<div id="lessonDetails">
    <div class="greenshades">
        <input name="addlesson"/>
        <input name="addsubject"/>
    </div>
    <div class="greenshades">
        <input name="addlesson"/>
        <input name="addsubject"/>
    </div>
    <div class="greenshades">
        <input name="addlesson"/>
        <input name="addsubject"/>
    </div>
</div>
<input type="button" onclick="validate()"/>

jquery: jQuery的:

function validate() {
    if ( $('#lessonDetails').children().length > 0 ) {

        $('#lessonDetails').children().each(function(){

            $(this).each(function() {               

                $('input[name="addlesson"]').each(function() {
                    if($(this).val() == "") {
                        alert("Please enter lesson title.");
                        return false;
                    }
                });

              $('input[name="addsubject"]').each(function() {
                    if($(this).val() == "") {
                        alert("Please enter subject.");
                        return false;
                    }
                });

            });
        });
    }
}

It's not working correctly. 它无法正常工作。 It gives more than one alert at time. 一次发出多个警报。

You don't need multiple each() , Modify the validate function as 您不需要多个each() ,将validate函数修改为

function validate() {
    var valid = true;
    $('#lessonDetails input[name="addlesson"]').each(function() {
        if ($(this).val() == "") {
            alert("Please enter lesson title.");
            valid = false;
            return false; //break loop only
        }
    });
    return valid;
}

Use the return value 使用返回值

<input type="button" onclick="return validate()"/>

$(this).each( doesn't makes any sense. $(this).each(没有任何意义。

$('#lessonDetails').find('input[name="addlesson"]').each(function () {

  if ($(this).val() == "") {
    alert("Please enter lesson title.");
    return false;
  }
});

I am finding all the nested 'input[name="addlesson"]' and iterating over them, rest of the logic is same so this will do the trick. 我发现所有嵌套的'input[name="addlesson"]'并对其进行迭代,其余逻辑相同,因此可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM