Home > Back-end >  How to get dynamic form value after click submit in Javascript?
How to get dynamic form value after click submit in Javascript?

Time:06-15

I have a dynamic form data which is loaded from backend. If there are static form, I can get value by document.getElementById("xxx"). However, if there are dynamic form which is unknown id, how can I get the value ? I would like to have these format to submit on it

    "answers" :[
    {
        "questionId" : 1002,
        "response" : "Yes"
    },{
        "questionId" : 1001,
        "response" : "No"
    }
]

Here is stackblitz link

CodePudding user response:

When you are looping over the form, you can generate class name or id from data fetched from backend, or you can construct new one.

CodePudding user response:

  1. Put your form fields inside a form tag (including the submit button).

  2. Give a class to the form e.g. custom-form

  3. Add a submit listener on the .custom-form selector.

    $('.custom-form').on('submit', function formSubmitHandler(event) {  
        // add logic here 
    });
    
  4. Inside the submit handler, get the input fields by doing something like this:

    const formInputs = $(this).find("input");  //this will retrieve all the input tags inside the form.
    

    You can now loop through them and perform your desired operation.

  • Related