嗨,我有一个表单,在其中我动态添加了一个新行,该新行由一个文本框和按钮按下时的复选按钮组成。然而,我需要某种方法来知道在发布数据中按下了哪些复选按钮,因此需要一个由每个复选按钮上的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);
});
有人能提出一个好的方法来帮助我在帖子数据中知道哪个文本字段,链接到哪个复选按钮,并知道它是否被按下了吗?
您可以使用$('input[type=button]').val()来获取单击按钮的value属性。或者,您可以使用$('input[type=button]').attr("name")来获取按钮的属性名称。
要查看是否选中单选按钮,请使用:$('#test').attr('checked');在这种情况下,你需要给你的支票箱一个id"测试"。
例如:
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);
});
在提交表单之前调用jquery函数,该函数将删除未选中的单选按钮的"name"属性,然后创建具有属性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"
要将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++;
});
});
演示