Reputation: 77
I'm hoping someone can help me. I have a form, when the form check box is checked a name attribute should be inserted in to the check box input field with a number at the end. I made something but is not exactly working
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>
Upvotes: 1
Views: 1046
Reputation: 23503
I think this is what you are going for:
<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>
If you want to add the value, just add checkbox.value = "your value";
under the checkbox.name
.
Here is the JSFiddle: https://jsfiddle.net/7teq1o9f/54/
This will output:
<input type="checkbox" class="item" name="my-list-item<1>" onclick="checkAddress(this)">
Upvotes: 2
Reputation: 1156
sorry its 2am here
var count = 0;
$('input[type="checkbox"]').change(function(){
$(this).attr('name',count++);
});
in plain js this.setAttribute("name", count++);
Upvotes: 1
Reputation: 8181
You may do the following in 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>
Upvotes: 2