向页面添加新元素时出现HTML ID问题

时间:2014-04-13 10:18:14

标签: javascript php jquery html post

大家好我有一个表单,我在其中动态添加一个新行,包括一个文本框和按下按钮上的复选按钮。但是,我需要某种方式来了解在帖子数据中按下了哪些检查按钮,因此需要一个值字段,其中包含每个检查按钮上的ID,代码如下所示:

<div id='1'>
    <div class="template">
        <div>
            <label class="right inline">Response:</label>
        </div>
        <div>
            <input type="text" name="responseText[]" value="" maxlength="400" />
        </div>
        <div>
            <input type="radio" name="responseRadio[]" value="" />
        </div>
    </div>
    <div>
        <input type="button" name="addNewRow" value="Add Row" />
    </div>
</div>

JS添加新行:

var $template = $('.template');
$('input[type=button]').click(function() {
    $template.clone().insertAfter($template);
});

有人能建议一个好的方法来帮助我在帖子数据中找到哪个文本字段,链接到哪个检查按钮,以及知道它是否被按下了?

3 个答案:

答案 0 :(得分:1)

您可以使用$(&#39;输入[type = button]&#39;。)val()来获取所点击按钮的value属性。或者您可以使用$(&#39;输入[type = button]&#39;)。attr(&#34; name&#34;)来获取按钮的属性名称。

要查看是否选中了单选按钮,请使用:$(&#39; #test&#39;)。attr(&#39; checked&#39;); 在这种情况下,您需要提供一个id&#39; test&#39;到你的chekbox。

例如:

var $template = $('.template');
$('input[type=button]').click(function() {
var name = $('input[type=button]').attr("name"); //Will return addNewRow
$('#test').attr('checked'); //Will return true or false for the radio/chekbox with the id test

$template.clone().insertAfter($template);
});

答案 1 :(得分:1)

在提交表单之前调用jquery函数,删除名称&#39;未选中的单选按钮的属性,然后创建一个包含属性name="responseRadio[]"value="false"的隐藏元素

$('form').submit( function(e) {
    $('.template').each( function() {
        var radio = $(this).find('input[type="radio"]');
        if( !radio.is(':checked') ) {
            radio.attr('name', false);
            radio.after( '<input type="hidden" name="responseRadio[]" value="false" />' );
        }
    });
});

上述代码将按正确的顺序包括所有文本输入和相应的无线电输入。未经检查的无线电将具有值"false"

答案 2 :(得分:0)

要为每个新创建的单选按钮和文本框添加id,请执行以下操作:

var i=2;
$(document).ready(function(e){
    $('html').on('click','input[type=button]',function() {
        //clone the last create .template div
        //so that when we insert, it gets added at the end
        var $template = $('.template:last');
        $clone = $template.clone(); 
        //find input with name responseText[] and add id text2 to it
        $clone.find("input[name='responseRadio[]']").attr('id','text'+i);
        //find input with name responseText[] and add id radio2 to it
        $clone.find("input[name='responseRadio[]']").attr('id','radio'+i);
        //insert the cloned element (at the end)
        $clone.insertAfter($template);
        //keep the counter incremented for the next element
        i++;
    });
});

<强> Demo