Click here to Skip to main content
15,885,782 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have multiple rows with input fields, and a seperate button for each row.

Since the form is dynamic, e.g some rows might appear from database, more rows can be added by a button, assigning each form/input an ID is difficult.

What is the easiest way for me to get the values from the input fields that are in the same row as the submit button?

(I can use Jquery)

What I have tried:

In the code below, my thought was to wrap each row in a form tag, and have the button submit the current form (e.g the one the button is within) in the onclick function.
But it seems to instead just submit the first form element on the page (which is a completely different form).

(wrapping each row in a form might be unnecessary?)

<form>
    <input name="name">
    <input name="phone">
    <button onclick"save(this.form)">Save</button>
</form>
<form>
    <input name="name">
    <input name="phone">
    <button onclick"save(this.form)">Save</button>
</form>
<form>
    <input name="name">
    <input name="phone">
    <button onclick"save(this.form)">Save</button>
</form>

Pseudocode for function:
function save(inputElements)
    {
        var phone = ???
        var name = ???
    }
Posted
Updated 18-Jan-22 15:26pm

1 solution

Have you tried querySelector?

function save(inputElements)
{
    var n = inputElements.querySelector("input[name='name']");
    var p = inputElements.querySelector("input[name='phone']");
    alert(n.value + "-" + p.value);
}
 
Share this answer
 
Comments
Jame_T 19-Jan-22 3:18am    
Thanks, but it only returns that element from the first row, regardless of which button i press...

I think the onclick save argument is what needs to be changed to return only the current form - but not sure how...
Richard Deeming 19-Jan-22 5:20am    
Once you fix the syntax error in your HTML - you're missing the = between onclick and "save(this.form)", the code from this solution works as expected:

Demo[^]
Jame_T 19-Jan-22 7:38am    
You're right, it does work, there was something else causing it to not work.
My rows/forms were inside another form tag like this: jsfiddle - and that caused it to only show the inputs in the first row, regardless of which button was pressed.
What's strange is in that jsfiddle it does work regardless... Anyway, once I moved the form end tag above it started working. Thanks a lot!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900