To create an array of inputs for test
, we can do:
<input name=test[]>
<input name=test[]>
...
But how can I manipulate each input in javascript/jQuery upon change, before submission? I figure I need to pass the index of a particular input from test[]
.
I'm stuck at $(this).index()
or $(this).parents().index()
, but these are index values of the DOM, they don't give the index value of the testa[]
, testb[]
, testc[]
arrays that's being triggered.
The reason for all this is because the POST
values for these checkboxes aren't passed, not even set, if they aren't checked. This messes up my database rows, hence I'm adding a textbox
for each row that will be passed (instead of passing the checkbox values) into the database.
Here's a working example that uses a FOR LOOP to accomplish my goal, but it seems inelegant and I'd rather not use a loop:
$(document).ready(function() {
$("input.test").change(function() {
rows = document.getElementsByName("LanguageLevels[]");
// ### This is the part I would really like to change - more elegant please?!?
var getIndex = 0;
testaArray = document.getElementsByName("testa[]");
testbArray = document.getElementsByName("testb[]");
testcArray = document.getElementsByName("testc[]");
for (var i = 0; i < testaArray.length; i++) {
if ((this == testaArray[i]) || (this == testbArray[i]) || (this == testcArray[i])) {
getIndex = i;
break;
}
}
// #### End of un-elegant code
rows[getIndex].value = this.value + " " + this.checked;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<!DOCTYPE html>
<div class="LL">
1. <input class="test" type="checkbox" name=testa[] value="test1">
2. <input class="test" type="checkbox" name=testb[] value="test2">
3. <input class="test" type="checkbox" name=testc[] value="test3">
<input name="LanguageLevels[]" id="LanguageLevels" size="37" placeholder="<--Please Choose one of the three" readonly>
</div>
<div class="LL">
1. <input class="test" type="checkbox" name=testa[] value="test4">
2. <input class="test" type="checkbox" name=testb[] value="test5">
3. <input class="test" type="checkbox" name=testc[] value="test6">
<input name="LanguageLevels[]" id="LanguageLevels" size="37" placeholder="<--Please Choose one of the three" readonly>
</div>