user1527388 user1527388 - 5 months ago 18
HTML Question

Javascript - Count of characters in a textfield returning NaN

I have a form I am trying to do, where if some one inputs text in a text field of a form, then clicks submit, I want to show him the cost of the sign (charactercount x price) i keep getting

NaN
!

Heres my Html:

<section class="sign" id="sign">
<h3 class="sign_header">CUSTOM SIGNAGE</h3>
<p class="sign_text">Enter Name, the cost per letter is $<span id="lettercost">6</span>.</p>
<form class="info_form">
<input type="text" id="inputletters" value="Example Name"><br>
<input type="button" value="Submit" class="button" id="getprice" onClick="getPrice();">
</form>


and here is my Javascript

function getPrice(){
var quantity = document.getElementById('inputletters').value.length;
var price = document.getElementById('lettercost');
var total = quantity*price;
var cost = document.getElementById('cost');
cost.textContent = total;
}

Answer Source

Here's a runnable example -- price was an object, you want .textContent, and parse those into numbers for this to work.

function getPrice() {
  var quantity = document.getElementById('inputletters').value.length;
  var price = document.getElementById('lettercost').textContent;
  console.log(typeof quantity, typeof price)
  var total = Number(quantity) * Number(price);
  var cost = document.getElementById('cost');
  cost.textContent = total;
}
<section class="sign" id="sign">
  <h3 class="sign_header">CUSTOM SIGNAGE</h3>
  <p class="sign_text">Enter Name, the cost per letter is $<span id="lettercost">6</span>.</p>
  <form class="info_form">
    <input type="text" id="inputletters" value="Example Name"><br>
    <input type="button" value="Submit" class="button" id="getprice" onClick="getPrice();">
  </form>
  <div id="cost"></div>
</section>