简体   繁体   中英

prepopulate form fields JSON response data

I am wanting to make a form that users have to submit their email to access and customers who already exist in my database trigger an API that returns a response from the server with all the data needed to complete the main form.. I am trying to have the main form display in a popup window and I am wanting to have the form repopulated with the server JSON response for users who have been previously registered so they only have to press the submit button in the main form popup window to complete and users who aren't registered will just have to manually enter their info in the main form.

here is a basic example server response for user emails that exist in my database:

{
    "execTime": 20,
    "billedTime": 20,
    "Table": [{
        "firstName": "JOHN",
        "lastName": "DOE",
    }]
}

and here is an example of the form I am trying to complete with

<form action="example.url" method="POST">
  <label for="firstName">First Name</label><br>
  <input type="text" id="firstName" name="firstName"><br>
  <label for="lastName">Last Name</label><br>
  <input type="text" id="lastName" name="lastName"><br>
<input type="submit" value="SUBMIT">
</form> 

What is the script I need to achieve this. I want the response data to repopulate the form fields for users that exist or for users that don't exist then it shows the blank form fields for users to enter their information

This is just a normal javascript object, check this reference on how to deal with Javascript objects

 const data = { "execTime": 20, "billedTime": 20, "Table": [{ "firstName": "JOHN", "lastName": "DOE", }] } document.getElementById('firstName').value = data.Table[0].firstName; document.getElementById('lastName').value = data.Table[0].lastName;
 <form action="example.url" method="POST"> <label for="firstName">First Name</label><br> <input type="text" id="firstName" name="firstName"><br> <label for="lastName">Last Name</label><br> <input type="text" id="lastName" name="lastName"><br> <input type="submit" value="SUBMIT"> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM