Javascript 如何保持无线电元素的值
已解决: 我使用jQuery允许用户向表单动态添加字段,并且我要求他们选择某些yes和no值。克隆行时,我需要保留输入单选元素上的值,但不保留文本元素上的值。我本以为这样就行了,但运气不好 我如何保持无线电元素上的值 此外,当上一个节点已选择无线电时,克隆将复制选择信息。我不想那样 HTML:Javascript 如何保持无线电元素的值,javascript,jquery,html,Javascript,Jquery,Html,已解决: 我使用jQuery允许用户向表单动态添加字段,并且我要求他们选择某些yes和no值。克隆行时,我需要保留输入单选元素上的值,但不保留文本元素上的值。我本以为这样就行了,但运气不好 我如何保持无线电元素上的值 此外,当上一个节点已选择无线电时,克隆将复制选择信息。我不想那样 HTML: <div class="dynamic-node"> <input type="text" name="custom-name[0]" value=""/>
<div class="dynamic-node">
<input type="text" name="custom-name[0]" value=""/>
<hr>
<input type="radio" name="haswood[0]" value="yes"/>Yes
<input type="radio" name="haswood[0]" value="no"/>No
<hr>
<input type="radio" name="hasmetal[0]" value="yes"/>Yes
<input type="radio" name="hasmetal[0]" value="no"/>No
<hr>
<input type="radio" name="hasplastic[0]" value="yes"/>Yes
<input type="radio" name="hasplastic[0]" value="no"/>No
</div>
<div class="clone-node">Add Row</div>
$cloneNode = $( ".clone-node" );
$cloneNode.click(function(){
var $newNode = $(".dynamic-node:last").clone(true);
$newNode.find('input').each(function() {
var $this = $(this);
$this.attr('name', $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
return '[' + (+$1 + 1) + ']';
}));
$this.val('');
});
$newNode.insertAfter('.dynamic-node:last');
});
解决方案:
<div class="dynamic-node">
<input type="text" name="custom-name[0]" value=""/>
<hr>
<input type="radio" name="haswood[0]" value="yes"/>Yes
<input type="radio" name="haswood[0]" value="no"/>No
<hr>
<input type="radio" name="hasmetal[0]" value="yes"/>Yes
<input type="radio" name="hasmetal[0]" value="no"/>No
<hr>
<input type="radio" name="hasplastic[0]" value="yes"/>Yes
<input type="radio" name="hasplastic[0]" value="no"/>No
</div>
<div class="clone-node">Add Row</div>
$cloneNode = $( ".clone-node" );
$cloneNode.click(function(){
var $newNode = $(".dynamic-node:last").clone(true);
$newNode.find('input').each(function() {
var $this = $(this);
$this.attr('name', $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
return '[' + (+$1 + 1) + ']';
}));
$this.val('');
});
$newNode.insertAfter('.dynamic-node:last');
});
多亏了下面的评论者,并借用了他们全新的视角,我通过稍微扩展代码并根据元素的类型和我的需要对其进行调整来解决这一问题:
$cloneNode = $( ".clone-node" );
$cloneNode.click(function(){
var $newNode = $(".dynamic-node:last").clone(true);
$newNode.find('input').each(function() {
var $this = $(this);
$this.attr('name', $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
return '[' + (+$1 + 1) + ']';
}));
if( $this.is('input:text') ) {
$this.val('');
}
if( $this.is('input:radio') ) {
$this.prop('checked', false);
}
});
$newNode.insertAfter('.dynamic-node:last');
});
您正在将值设置为空字符串。如果希望值保持不变,请不要这样做。只需将
checked
属性设置为false。是$this.val(“”)导致了问题吗?ARHG,,,太棒了。我重复使用了一个旧代码,今天早上我需要一双新眼睛,显然,谢谢!我将不得不进一步分解代码:)还有迈克,这是一个有用的建议。谢谢