[英]insert name attribute when check box is checked
我希望有人能帮助我。 我有一个表单,当选中表单复选框时,应将名称属性插入到复选框输入字段中,并在末尾添加一个数字。 我做了点什么,但工作不正常
when checkbox is checked it should look like this:
<input type="CHECKBOX" class="item" name="my-list-item<0>" value="value">My Item<br>
<input type="CHECKBOX" class="item" name="my-list-item<1>" value="value">My Item<br>
<form>
<input type="CHECKBOX" class="item" value="value">My Item<br>
<input type="CHECKBOX" class="item" value="value">My Item<br>
<input type="CHECKBOX" class="item" value="value">My Item<br>
<input type="CHECKBOX" class="item" value="value">My Item<br>
</form>
<script>
function prepareSearchForm(form){
var count = 0;
$(form).children('.item').each(function(o){
var cityDOM = document.createElement('input');
itemDOM.name = "my-list-item<" + (count++) + ">";
itemDOM.value = o.value;
form.appendChild(itemDOM);
});
}
</script>
我想这就是你要的:
<form>
<input type="checkbox" class="item" onclick="checkAddress(this)" />My Item<br>
<input type="checkbox" class="item" onclick="checkAddress(this)" />My Item<br>
<input type="checkbox" class="item" onclick="checkAddress(this)" />My Item<br>
<input type="checkbox" class="item" onclick="checkAddress(this)" />My Item<br>
</form>
<script>
function checkAddress(checkbox)
{
if (checkbox.checked)
{
var count = 0;
var checkboxes = document.getElementsByClassName("item");
for(var ii = 1; ii < checkboxes.length; ii++){
if(checkboxes[ii].checked){
count++;
}
checkbox.name = "my-list-item" + count;
}
}
}
</script>
如果要添加值,只需添加checkbox.value = "your value";
在checkbox.name
。
这是JSFiddle: https ://jsfiddle.net/7teq1o9f/54/
这将输出:
<input type="checkbox" class="item" name="my-list-item<1>" onclick="checkAddress(this)">
您可以在jQuery中执行以下操作。
$('input:checkbox').change(function() { $(this).attr({ 'name': 'my-list-item<' + $(this).data("index") + '>' }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form> <input type="checkbox" class="item" value="value" data-index="0" />My Item<br/> <input type="checkbox" class="item" value="value" data-index="1" />My Item<br/> <input type="checkbox" class="item" value="value" data-index="2" />My Item<br/> <input type="checkbox" class="item" value="value" data-index="3" />My Item<br/> </form>
对不起,这里凌晨2点
var count = 0;
$('input[type="checkbox"]').change(function(){
$(this).attr('name',count++);
});
用普通的js this.setAttribute(“ name”,count ++);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.