Jump to content

convert input="text" value into a number


seany123

Recommended Posts

        <script language="javascript" type="text/javascript">  
            function updatetestid() {
                
                var test = document.getElementById('number').value;
                total = test + 10;
                
                document.getElementById('testid').innerHTML = total; 
            }   
        </script>
        <input type="text" onKeyUp="updatetestid();" name="text" id="number"/>
        <span id="testid">here</span>

currently this will treat #number as a string, but i want to be able to do some maths with the value

 

what am i doing wrong?

 

thanks

Link to comment
https://forums.phpfreaks.com/topic/296352-convert-inputtext-value-into-a-number/
Share on other sites

All HTML form data is a string. So you just need to convert it to a number in javascript before doing math.

 

var test = parseInt(document.getElementById('number').value);  //use parseInt() to convert to an integer. There are others for float, etc.
total = test + 10;

 

All HTML form data is a string. So you just need to convert it to a number in javascript before doing math.

var test = parseInt(document.getElementById('number').value);  //use parseInt() to convert to an integer. There are others for float, etc.
total = test + 10;

 

thanks for your response thats exactly what i was looking for!

 

i have another problem, i want to display the result in more than 1 place on my page so i created another <span id="testid"></span> but it only shows the result in the first span, should this happen? is there a way to show it in both?

i realised that you cant have 2 ids, so i changed them to class however i was wondering if there was a more efficient way of assigning all class' in the array the same value.

 

currently im doing

document.getElementsByClassName('testclass')[0].innerHTML = "result here";
document.getElementsByClassName('testclass')[1].innerHTML = "result here";

surely there must be a better way?

jQuery. Or another Javascript framework. You're getting into the realm of things that are awkward and tedious to do in plain Javascript.

 

For example, what you're looking for in jQuery is done with

$(".testclass").html("result here");

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.