简体   繁体   English

验证新创建的输入

[英]Validating newly created inputs

I'm using small attachment form with dynamically created inputs. 我正在使用带有动态创建输入的小型附件形式。

These new inputs are created this way: 这些新输入是通过以下方式创建的:

function addAttachmentRow() {
    var htmlRow = '<tr><td><input type="text" name="file_name[]"></td></tr>';
    $("#attachment_list").append(htmlRow);
}

and I am trying to prepare validating function, but this code: 并且我正在尝试准备验证功能,但是这段代码:

$( document ).ready(function() {
    $('input[name^="file_name"]').each(function() {
        $(this).keydown(function(){ 
            if ($(this).val().length < 2) {
                $(this).css("background-color", "#FFCCCC");
                $(this).css("border", "1px solid #665252");
                $(this).css("color", "#B20000");
            } else {
                $(this).css("background-color", "#F5FFEB");
                $(this).css("border", "1px solid #5CE65C");
                $(this).css("color", "#145214");
            }
        }); 
    });
});

but it only applies to the very first element which is created statically. 但它仅适用于静态创建的第一个元素。 It does not effect elements, created when "addAttachmentRow" is clicked and new input added. 它不影响单击“ addAttachmentRow”并添加新输入时创建的元素。

Changing it to 更改为

$('input[name^="file_name[]"]').each(function() {

doesn't help either, and I just need to have [] in input's name. 也无济于事,我只需要在输入名称中使用[]即可。

Any ideas? 有任何想法吗?

Thanks in advance. 提前致谢。

Yes. 是。 It happens. 它发生了。 It doesn't select the element with that code. 它不会选择带有该代码的元素。 You will need to use $(document).on method instead of this. 您将需要使用$(document).on方法代替此方法。

Solution : 解决方案

Use this code 使用此代码

$(document).on('event', 'selector', function() {
    // code
});

eg 例如

$(document).on('each', 'input[name^="file_name[]"]', function() {
    alert('Event fired!');
});

You need to bind event with the document for dynamic elements: 您需要将事件与文档绑定以获取动态元素:

$(function(){
  $(document).on('keydown', 'input[name^="file_name"]', function(e) {
    /* to do here */
  });
});

Try this demo: 试试这个演示:

 $(function() { $(document).on('keydown', 'input[name^="file_name"]', function(e) { var err = 2 > $.trim(this.value).length; $(this).toggleClass('rest', !err).toggleClass('err', err); }); }); function addAttachmentRow() { var htmlRow = '<tr><td><input type="text" name="file_name[]"></td></tr>'; $("#attachment_list").append(htmlRow); } 
 .rest { background-color: #F5FFEB; border: 1px solid #5CE65C; color: #145214; } .err { background-color: #FFCCCC; border: 1px solid #665252; color: #B20000; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <input type='button' value='Add' onclick='addAttachmentRow()' /> <table id='attachment_list'> </table> 

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

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