Search code examples
javascripthtmlfunctionlabeltypeconverter

Trying to Convert Label that is number to int


I've been trying to convert a label to an int to do an equation. I haven't been able to use ConvertToInt32() or ParseInt(). I've been getting back NaN each time. Please help! Here's my code:

    <div id="width"> <strong>Roll Width: </strong><label id="lblRollWidth"       type="number">25</label></div>
    </asp:Panel>
</div>
</div>


 <input type="text" name="input1" id="input1" value="">
<input type="text" name="input2" id="input2" value="">
    <a href="javascript: void(0)" onClick="calc()">Calculate</a>
        <input type="text" name="output" id="output" value="">

  <script>

 function calc(){

 var textValue1 = document.getElementById('input1').value;
 var textValue2 = document.getElementById('input2').value;
 var textValue3 = document.getElementById('lblRollWidth').value;




       document.getElementById('output').value = textValue1 * textValue2 * textValue3; 
}
  </script>

Solution

  • change :

    var textValue3 = document.getElementById('lblRollWidth').value;
    

    to

    var textValue3 = +document.getElementById('lblRollWidth').innerText;
    

    because it is a label, therefore to get its value you have to use .innerText.

    Also, not mandatory, but recommendended, change:

     var textValue1 = document.getElementById('input1').value;
     var textValue2 = document.getElementById('input2').value;
    

    to:

     var textValue1 = +document.getElementById('input1').value;
     var textValue2 = +document.getElementById('input2').value;
    

    So that they will be casted as numbers.

    Fiddle: http://jsfiddle.net/m1brLkqx/

    Also, as a side note, NaN is being thrown because of the label, the rest was working.