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;
}
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.
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()
.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With