Issue
I have a form that has multiple rows of the same information, like this:
<form>
<input name="a[]">
<input name="b[]">
<input name="d[]">
<input name="e[]">
<br>
<input name="a[]">
<input name="b[]">
<input name="d[]">
<input name="e[]">
<br>
<input name="a[]">
<input name="b[]">
<input name="d[]">
<input name="e[]">
...
</form>
I'm simplifying my needs to make it easier to explain. When someone updates an element on one row, I want to detect that that row was changed, and be able to programatically change the other inputs on the same row.
For example, if someone changes the second b[], i want to be able to programatically update the second c[].
It needs to be generic so it can run on any similar form. I've added a change event for every element in the form, but I'm not sure how to derive the index from each input. Like, how do I know its the "second" a[], and then how do I get the "second" b[]?
I'm imagining something like this:
inputs = resultForm.querySelectorAll('input, select, textarea')
for (var i = 0; i < inputs.length; i++) {
inputs[i].onchange = function(e) {
//something like this is what I'm after
row = this.name.index;
document.getElementsByName("b[]")[row].value = "a form element in this row was clicked";
}
}
The only thing that comes to mind is to grab every "a[]" and loop through them to see if they match the "this", then every "b[]", then "c[]" until I find the element that changed, and use it's index to identify the row number.
That's challenging cause I need it to be a generic solution, my fields wont always be named a, b, c, etc.
Any ideas?
Solution
What I ended up doing is on the window load event, I grab every INPUT, SELECT, and TEXTAREA in the form. Then I loop through them, keeping track of how many elements I have by each name. 10 named "name" and 10 named "address". Using that number I add rowid attribute to each element. Then in the events I can just read that rowid attribute.
<form>
<input name="a[]" rowid="1">
<input name="b[]" rowid="1">
<input name="d[]" rowid="1">
<input name="e[]" rowid="1">
<br>
<input name="a[]" rowid="2">
<input name="b[]" rowid="2">
<input name="d[]" rowid="2">
<input name="e[]" rowid="2">
<br>
<input name="a[]" rowid="3">
<input name="b[]" rowid="3">
<input name="d[]" rowid="3">
<input name="e[]" rowid="3">
...
</form>
Answered By - Kmus
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.