2

Having difficult time finding solution way to take html form data and transform it into json file using javascript

Looked many places but unable to find anything.

<!DOCTYPE html>
<html>
<body>

 <p>Enter names in the fields, then click "Submit" to submit the form: 
 </p>

 <form id="frm1" action="/">
 First name: <input type="text" name="fname"><br>
 Last name: <input type="text" name="lname"><br><br>
 <input type="button" onclick="myFunction()" value="Submit">
 </form>

 <script>
 function myFunction() {
 document.getElementById("frm1").submit();
 }
 </script>

 </body>
 </html>

Just need to know how to transfer the html form data into json not using php but javascript.

2 Answers 2

1
function formSerialize(formElement) {
   const values = {};
   const inputs = formElement.elements;

   for (let i = 0; i < inputs.length; i++) {
       values[inputs[i].name] = inputs[i].value;
   }
   return values;
}

Add this function in your script and call function like this

formSerialize(document.getElementById("frm1"))

while will give you json format of your form data like this

{fname: "wer", lname: "wer", "": "Submit"}

Hope this will help you.

Sign up to request clarification or add additional context in comments.

2 Comments

It definitely helps and very greatful. Since Im new to Javascript and just learning would like to actually have context such as calling the multiple functions and is this JQUERY? Anything more on the output would be helpful to me.
No Its just plain javascript @jmichael
0

I'm not sure how do you want your end product looks like, but here's the closest solution without modifying too much of your code.

First: change your inputs to have "id"s instead of name (or both, point is you need IDs)

First name: <input type="text" id="fname"><br>
Last name: <input type="text" id="lname"><br><br>

Second: have your script like the following:

 <script>
 function myFunction() {
    let output = {
        fName: document.getElementById("fname").value, 
        lName: document.getElementById("lname").value
    };
    console.log(output);
 }
 </script>

Hope that helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.