我希望有人能帮助我。我有一个表单,当表单复选框被选中时,名称属性应该插入到复选框输入字段中,末尾有一个数字。我做了一些东西,但并不完全有效
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.name
下添加checkbox.value = "your value";
即可。
这是 JSFiddle:https://jsfiddle.net/7teq1o9f/54/
这将输出:
<input type="checkbox" class="item" name="my-list-item<1>" onclick="checkAddress(this)">
关于javascript - 选中复选框时插入名称属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29200120/