rst
rst

Reputation: 2714

Read value of input field and automatically assign var type using javascript/jquery

So I have dozens of input fields and need to parse each of them into a object with key/value pairs. I can do that easily using this here

var myobj = {};
$(this).find('.stuff').each(function (e) {
  var key = $(this).attr('name');
  var val = $(this).val();
  myobj[key] = val;
}).promise().done(function (e) {
   // do more stuff
});

However, each value is parsed as string but some of them are int and some of them are decimals. How can I parse them automatically? Do I need to add e.g. a class to each input and parse them using e.g. switch?

Upvotes: 0

Views: 106

Answers (2)

user8313246
user8313246

Reputation:

You could try this:

if(!isNaN(val)) {
    val = Number(val);
}

Try placing that under the line

var val = $(this).val();

Upvotes: 1

Difster
Difster

Reputation: 3270

Use $.type() to test for the difference then act accordingly.

var x = 123;
var y = $.type(x);
alert(y); //alerts "number"

You can find the documentation here.

Upvotes: 1

Related Questions