Search code examples
javascripthtmljsonform-data

FormData converts numeric input field to string


I have REST backend and an HTML frontend. I use forms on the frontend to send requests to the backend. In order to do this, I use FormData to convert from the form object to a JSON object that I can send to the REST backend.

Heres the form

<form id="form">
    <label for="string">string:</label><br>
    <input type="text" id="string" name="string" value="string"><br>
    <label for="number">number:</label><br>
    <input type="number" id="number" name="number" value="12"><br><br>
    <input type="submit" value="Submit">
</form> 

And the is is the function I use to convert the form to a json object:

window.onload = function(){
    const form = document.getElementById('form')
    form.onsubmit=send
}

function send(e){

    e.preventDefault()

    var data=new FormData(e.target)
    data=Object.fromEntries(data)
    console.log(data)


}

Unfortunately, FormData converts number inputs to strings, but the backend expects actual numbers. I know I could just reconvert them back to numbers manually for every form field, but this isn't the only form in the application and I would like to be able to reuse the same code for submitting to different endpoints.

{
  "string": "string",
  "number": "12"
}

So is there a way to either make FormData not convert the numbers to string, an alternative to FormData, or a way to autmatically reconvert strings to numbers, if the original input was a number input?


Solution

  • Everything will be in string format and in key-value pairs when you use formData. Please check here for more explanation