addition in javascript

Discussion in 'JavaScript' started by ronie_imaginet, Jun 5, 2008.

  1. #1
    i made 2 textbox, the first textbox has a value of 12 and the other one is 20, when i click on the button result, my result textbox displays 1220, what should i do in order for my result textbox to display 32?
     
    ronie_imaginet, Jun 5, 2008 IP
  2. xlcho

    xlcho Guest

    Messages:
    532
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Use parseInt() when calculating the result. Now the script is concatinating the input from the textboxes, cause they are parsed as strings. Something like that:
    result.value = parseInt(textbox1.value)+parseInt(textbox2.value);
    Code (markup):
     
    xlcho, Jun 5, 2008 IP
  3. ronie_imaginet

    ronie_imaginet Peon

    Messages:
    7
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    anyway, is there a way where i can lock a textbox. where in a user cannot type a string. if the user type a string, the value of the textbox will be null?

    thanks
     
    ronie_imaginet, Jun 5, 2008 IP
  4. ronie_imaginet

    ronie_imaginet Peon

    Messages:
    7
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    parseInt is corect, but wen i inputted 1.50, the result textbox dispalys 1 instead of 1.50! is there anyway to fix this?
    thank you so much!
     
    ronie_imaginet, Jun 6, 2008 IP
  5. xlcho

    xlcho Guest

    Messages:
    532
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Not quite sure i understand you, but i'll explain some stuff anyway. to lock the textbox use the following:
    document.getElementById('mytextbox').disabled = 'disabled';
    Code (markup):
    Be aware that disabled input fields will not be send when a form is submitted. This could cause you some trouble too.
    Here's a little method i'd use to limit the user to typing numbers only:
    <script type='text/javascript'>
    function checkInput(str)
    {
            if(isNaN(str))
                    return str.replace(/[^0-9]+/g,'');       
            else
                    return str;
    }
    </script>
    <input type='text' onkeyup='this.value = checkInput(this.value)'>
    
    Code (markup):
     
    xlcho, Jun 6, 2008 IP
  6. xlcho

    xlcho Guest

    Messages:
    532
    Likes Received:
    8
    Best Answers:
    0
    Trophy Points:
    0
    #6
    Yes, use parseFloat() insted. parseInt returns integers, parseFloat returns floating point numbers.
     
    xlcho, Jun 6, 2008 IP