Reputation: 189
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
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
Reputation: 19560
this
is the element.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
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
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;
});
...and drop the inline event handler.
To check if parseFloat()
returns NaN
, use isNaN()
.
Upvotes: 6