jquery动态子选择结合last和form元素

时间:2013-11-01 07:09:27

标签: javascript jquery forms selector

更新

整理正在进行的解决方案并添加一些额外的细节

我有一个表单区域,可以根据模板创建克隆。为了确保表单按顺序传输,脚本在发送时通过表单附加一个定义当前批处理集的数字。以下是对正在发生的事情的过度简化表示:

<form>
    <div class="batch-template">
        <div class="batch-piece">
            <a class="clone" />
            <input name="test-input">
            <input name="another-test-input">
            <select name="a-drop-down">
        </div>
    </div>
    <div class="batch-paste-area">
    </div>
</form>

页面开始时:

  • “批处理模板”的内容存储在对象变量
  • 原始模板已从页面中删除
  • 模板的一个实例附加到“batch-paste-area”

以下是点击两次后创建的输出示例。

<form>
    <div class="batch-template">
    </div>
    <div class="batch-paste-area">
        <div class="batch-piece">
            <a class="clone" />
            <input name="test-input">
            <input name="another-test-input">
            <select name="a-drop-down">
        </div>
        <div class="batch-piece">
            <a class="clone" />
            <input name="test-input">
            <input name="another-test-input">
            <select name="a-drop-down">
        </div>
    </div>
</form>

提交表单时:在序列化之前,我希望脚本循环遍历“批处理粘贴区域”中的每个“批处理”,并将计数值添加到每个表单字段名称的末尾。继续上面的设置,结果(对浏览器)看起来如下所示:

<form>
    <div class="batch-template">
    </div>
    <div class="batch-paste-area">
        <div class="batch-piece">
            <a class="clone" />
            <input name="test-input1">
            <input name="another-test-input1">
            <select name="a-drop-down1">
        </div>
        <div class="batch-piece">
            <a class="clone" />
            <input name="test-input2">
            <input name="another-test-input2">
            <select name="a-drop-down2">
        </div>
    </div>
</form>

到目前为止,我可以遍历粘贴区域内的每个输入,或者只选择最后一个。

选择最后一个批次很简单:

var intCount = 1;
$('.batch-paste-area .batch-piece').each(function(){
    /* 
    * Would like to be able to loop through form fields here 
    * Below is an attempt to select all form fields for current set 
    */
    $(this + ' input, '+ this + ' select').each(function() {
        var strName = $(this).attr('name') + intCount;
        $(this).attr('name', strName);
    });
    intCount++;    
});

1 个答案:

答案 0 :(得分:0)

令人沮丧的是,我事先尝试过正确的解决方案,但当时忘了使用逗号!

var intCount = 1;
$('.batch-paste-area .batch-piece').each(function(){
    /* 
    * Would like to be able to loop through form fields here 
    * Below is an attempt to select all form fields for current set 
    */
    $(this).find("input, select").each(function() {
        var strName = $(this).attr('name') + intCount;
        $(this).attr('name', strName);
    });
    intCount++;    
});