Adding jQuery

I am trying to add via jquery event and I get 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; } 
+6
source share
4 answers

The code should be:

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

Inline onchange is actually an anonymous function:

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

So, "this" is an argument called "ok" in the scope of valueadd. However, as others have argued, you probably want to use jquery bind, so the "this" inside valueadd will point to an element.

+6
source

this is a reserved word in JavaScript, so you cannot use it in the signature of a function argument.

I would probably change this code to ...

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

jsFiddle .

... and release the inline event handler.

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

+5
source

You should do it just like this:

 <input type="hidden" id="skillcount" name="skillcount" value="3" onchange="valueadd()"/> function valueadd() { var value=parseFloat(this.value)+1; } 
+3
source
  • Assign your behavior with jQuery since you have this and use it anyway. Do not use built-in event handlers
  • A function related to jQuery is executed in the scope of the element on which the event occurred. This means that this is an element.
  • this cannot be used as a parameter name or anything other than to access an object in a scope.

Using:

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

Source: https://habr.com/ru/post/893224/


All Articles