遍历动态添加的元素数组 [英] Looping through array of dynamically-added elements

查看:126
本文介绍了遍历动态添加的元素数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对jQuery来说是新手,在我无法弄清楚的事情上寻求帮助.

New to jQuery, requesting assistance with something I'm having trouble figuring out.

一个克隆的表行包含一个<input type="text" name="dt[]" id="dt1">字段.下面是被克隆的模板行.

A cloned table row contains an <input type="text" name="dt[]" id="dt1"> field. Below is the template row that gets cloned.

<table id="MyTable" name="MyTable">
    <tr name="tr3" id="tr3">
        <td>
            <input type="text" name="dt[]" id="dt1">
        </td>
        <td>
            <input type="file" name="fff[]" id="ff1">
        </td>
    </tr>
</table>

用户可能会创建其中几个字段,而我正在尝试弄清楚如何遍历所有字段并在提交表单之前验证其中是否包含文本.

The user could potentially create several of these fields and I am trying to figure out how to loop through them all and verify there is text in them before submitting the form.

请注意,我必须使用jQuery .on()方法来访问表单元素.循环需要如何编码?最初,我一直在尝试此操作(已编辑):

Note that I must use the jQuery .on() method to access the form elements. How would the loop need to be coded? Initially, I've been trying this (EDITED):

$(document).on('click','#sub1',function() {
    var d1 = $("[name^=dt]").val();
    alert(d1);
    if (d1 !=""){
        $("#TheForm").submit();
    } else {
        alert("Empty fields!");
    }
});

这:

var d1 = $("#dt1").val();
alert(d1);

这:

var d1 = $("#^dt").val();
alert(d1);

但无法获取数据.

根据要求,此代码克隆该行:

As requested, this code clones the row:

$(document).on('click', '#add_row', function() {
    $("table#MyTable tr:nth-child(4)")
        .clone()
        .show()
        .find("input, span").each(function() {
            $(this)
                .val('')
                .attr('id', function(_, id) {
                    var newcnt = id + count;
                    return id + count;
                    });
        })
        .end()
        .appendTo("table")
        ;

    count++;
    if (count == 2) {
        $('#add_row').prop('disabled', 'disabled');
    }
}); //end add_row Function

推荐答案

您的HTML格式不正确.您应该这样做:

Your HTML is not in correct format. you should do:

<input type="text" name="dt[]">

然后像这样循环遍历:

$('input[name^=dt]').each(function() {
  // code
  alert( this.value ); // $(this).val()
});

您尝试执行的操作无法通过id属性实现,但是可以通过name属性实现. id应该始终是唯一的 .

What you're trying to do can not be possible with id attribute, but possible with name attribute. id should always be unique.

您可以对所有input使用通用的class名称,然后像这样循环遍历:

You can use a common class name to all inputs and then loop over then like:

$('input.common_cls').each(function() {
  // code
});


注意

"#^dt"根本不是有效的选择器.正确的语法是


Note

"#^dt" is not a valid selector at all. Correct syntax would be

'input[name^=dt]'

OR

OR

input[id^=dt].

// this function will return true if no empty
// input exists, otherwise it will return false

function noEmptyExists() {
    return $('input[name^=dt]').filter(function() {
        return !$.trim( this.value );
    }).length === 0;
}

$(document).on('click','#sub1',function() {
   if( noEmptyExists() ) {
      alert('Success');
   } else {
      alert('Failed');
   }
});

工作示例

this.val()是错误的.

将此行更改为:

$(this).val()


在聊天"中讨论并解决了克隆问题之后

完整代码


After a discussion in Chat and after solving the clone issue

Full code

$(document).ready(function() {
    var count = 1;
    alert('doc ready');
    var row = $("table#MyTable tr:eq(1)");
    $(document).on('click', '#sub1', function() {
        if (noEmptyExists()) {
            alert('Success');
        } else {
            alert('Failed');
        }
    });

    $(document).on('click', '#add_row', function() {
        row.clone(true).find("input").each(function() {
            $(this).val('').attr('id', function(_, id) {
                var newcnt = id + count;
                return id + count;
            });
        }).end().appendTo("table");
    });

});

function noEmptyExists() {
    return $('input[name^=dt]').filter(function() {
        return !$.trim(this.value);
    }).length === 0;
}

工作示例

这篇关于遍历动态添加的元素数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆