softcode softcode - 1 month ago 10
jQuery Question

Number parsing working in console but not in script

Here's my simple function, which is being called on the element as

onclick="incrementValue(this)"


function incrementValue(plusElement) {
var choicesLeft = jQuery("#choicesLeft");

choicesLeft.innerHTML = Number(choicesLeft.innerHTML) - 1;
console.log(choicesLeft.innerHTML);
};


The
console.log
line prints out a NaN in the console.

However when I enter this line in the console:

choicesLeft.innerHTML = Number(choicesLeft.innerHTML) - 1;


The expected behavior occurs.

Any ideas ?

Answer

innerHTML will not work here since you call it on jQuery object.

Use text() instead of innerHTML :

choicesLeft.text( Number(choicesLeft.text()) - 1 );

Hope this helps.

function incrementValue() {
  var choicesLeft = jQuery("#choicesLeft");

  choicesLeft.text( Number(choicesLeft.text()) + 1 );
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onClick='incrementValue()'>Increment</button>
<br>
<span id='choicesLeft'>0</span>