Clay Smith
Clay Smith

Reputation: 189

Jquery math addition

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;
}

Upvotes: 6

Views: 32716

Answers (4)

Dennis
Dennis

Reputation: 32598

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.

Upvotes: 6

JAAulde
JAAulde

Reputation: 19560

  1. Assign your behavior with jQuery since you have it available and are using it anyway. Don't use inline event handlers
  2. A function bound by jQuery is executed in scope of the element on which the event occurred. Which means this is the element.
  3. this cannot be used as a param name or anything other than to access the object in scope.

Use:

<input type="hidden" id="skillcount" name="skillcount" value="3" />

<script type="text/javascript">
    $( '#skillcount' ).bind( 'change', function()
    {
        var value = parseFloat( $( this ).val() ) + 1;
    } );
</script>

Upvotes: 1

brenjt
brenjt

Reputation: 16297

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;
}

Upvotes: 3

alex
alex

Reputation: 490263

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().

Upvotes: 6

Related Questions