Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery math addition

Tags:

jquery

math

I'm trying to add through a jquery event and I'm getting NaN. What am I missing?

   <input type="hidden" id="skillcount" name="skillcount" value="3" onchange="valueadd(this)"/>

   function valueadd(ok){
var value=parseFloat($(this).val())+1;
}
like image 906
Clay Smith Avatar asked Jul 21 '11 01:07

Clay Smith


3 Answers

The code should be:

function valueadd(ok){
  // "this" inside here refers to the window
  var value=parseFloat(ok.value)+1;
} 

The inline onchange is actually an anonymous function:

function() {
   //"this" inside here refers to the element
   valueadd(this);
}

So "this" is an argument that gets called "ok" in the valueadd scope. As the others have stated, though, you probably want to use jquery's bind so "this" inside of valueadd will point to the element.

like image 89
Dennis Avatar answered Nov 01 '22 05:11

Dennis


this is a reserved word in JavaScript, so you can't use it in the function argument signature.

I'd probably change that code to...

$('#skillcount').change(function() {
    var value = parseFloat($(this).val()) + 1;
});

jsFiddle.

...and drop the inline event handler.

To check if parseFloat() returns NaN, use isNaN().

like image 6
alex Avatar answered Nov 01 '22 07:11

alex


You should be able to do it simply like so:

<input type="hidden" id="skillcount" name="skillcount" value="3" onchange="valueadd()"/>

function valueadd()
{
    var value=parseFloat(this.value)+1;
}
like image 3
brenjt Avatar answered Nov 01 '22 05:11

brenjt