0

Hi I'm trying to check the value of DOM with:

if ($('#ATTN').val() == '') {               
    $('#ATTN').val(0);
} else {
    iattn=$('#ATTN').val();
    alert(iattn);

    if(typeof iattn == 'number'){
        alert('oh');
    }
}

but it returns nothing. Also no error shown.

p.s.w.g
  • 136,020
  • 27
  • 262
  • 299
Bineesh
  • 476
  • 1
  • 4
  • 18

2 Answers2

1

This line

iattn=$('#ATTN').val();

Returns a string.

If you want to see whether it can be converted to an integer, then what you want is this:

iattn=parseInt($('#ATTN').val());
if (iattn) {
    alert("oh");
}

Use parseFloat rather than parseInt if you want a more general number test.

If you want to check that the result of parsing matches the input, use something like this:

iattn=$('#ATTN').val();
if (iattn == parseInt(iattn)) {
    alert("oh");
}

A simpler check, which won't actually convert anything to a number, and will allow all number formats (eg 2.3, 0x3, +23) is this:

if (!isNaN(iattn)) {
    alert("oh");
}

Credit to @p.s.w.g from a comment.

Chris Lear
  • 6,057
  • 1
  • 14
  • 25
  • 1
    but chances are there the user give a text value by mistake and parseint will convert that too to an integer . that will make mess ! – Bineesh Jun 30 '16 at 14:50
  • 1
    If the user gives a text value that can't be converted to an integer, `iattn` will be `NaN` and the if condition will fail. – Chris Lear Jun 30 '16 at 14:52
  • I've updated with a check that the parsed value is similar to the input, to deal with cases like "2sdfsdsdf". But then if the user enters eg "2.0" the check will fail. – Chris Lear Jun 30 '16 at 14:55
  • I believe `if (!isNaN(iattn))` would be equivalent for all cases except the empty string (you could use `if (iattn && !isNaN(iattn))` if necessary). – p.s.w.g Jun 30 '16 at 15:07
0

.val() return a DOMString(string)

so typeof iattn always will be a string

if you want the typeof number you need convert to int

using parseInt(iattn) or parseFloat(iattn)

HudsonPH
  • 1,708
  • 2
  • 19
  • 34