1

I want to convert all form values to JSON so that I can send the JSON as body in my AJAX POST. I found this existing solution online:

function getFormData($form){
    var unindexed_array = $form.serializeArray();
    var indexed_array = {};

    $.map(unindexed_array, function(n, i){
        indexed_array[n['name']] = n['value'];
    });

    return indexed_array;
}

Usage:

var $form = $("#form_data");
var data = getFormData($form);

However, this approach (source) converts all values to type string, it does not preserve numbers as integers. I could not come up with a way to preserve the type of the values. What is the best way to do this?

HTML:

<form id="myform">
    <div>
      <label>Number: </label>
      <input id="mynum" type="number" name="mynum"/>
    </div>
    <div>
      <label>name: </label>
      <input id="myname" type="text" name="myname"/>
    </div>
</form>
b11
  • 67
  • 1
  • 1
  • 9

1 Answers1

2

That is because all input values are by default of type string. If you want to convert the type to number type you have to do that manually.

One way to do that by looping through the JSON and use a manual function to parse string value back to the number type.

To create a manual function: http://pietschsoft.com/post/2008/01/14/JavaScript-intTryParse-Equivalent

The following code shows even if the input type is number, the type is actually string:

let type;
function checkFormData(){
  type = document.getElementById('mynum').value;
  console.log('The type of input#mynum is: ' +typeof type);
  return false;
}
<form id="myform" onsubmit=" return checkFormData()">
  <div>
    <label>Number: </label>
    <input id="mynum" type="number" name="mynum"/>
  </div>
  <div>
    <label>name: </label>
    <input id="myname" type="text" name="myname"/>
  </div>
  <input type="submit" value="Submit"/>
</form>
Mamun
  • 66,969
  • 9
  • 47
  • 59
  • But for some inputs I have input type="number", does that not help at all in this case – b11 Dec 07 '17 at 05:21
  • Can you add some html markup in the question to have a look? – Mamun Dec 07 '17 at 05:23
  • see added html in post – b11 Dec 07 '17 at 05:27
  • @b11, though the type of `input` is number, it is actually a `string`. Please have a look my updated answer to check that...thanks. – Mamun Dec 07 '17 at 05:47
  • So I have to use a manual function on every field of the form? That creates n number of function calls if there are n number of fields. Is there a better way? – b11 Dec 07 '17 at 05:58
  • Yes, if you need multiple number of field's value back to the `number` type. This is actually a enhanced version of built-in `parseInt` we normally use. If you are sure about the input is `number` only, then you can use `parseInt` as well....thanks. – Mamun Dec 07 '17 at 06:04