Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 868
user2741831 Avatar asked Apr 24 '26 16:04

user2741831


1 Answers

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

like image 55
Md. Al Amin Bhuiyan Avatar answered Apr 27 '26 06:04

Md. Al Amin Bhuiyan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!