Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate text box in Javascript by clicking on button [closed]

I am trying to populate a text box on a form by clicking on form buttons. Below is code I have so far - modified this code from a select box example -

<!DOCTYPE html>
<html>

<head>
    <script>
        function moveNumbers(){
            var no=document.getElementById("no");
            var txt=document.getElementById("result").value;
            txt=txt + option;
            document.getElementById("result").value=txt;
        }
    </script>
</head>

<body>
    <form>
        Select numbers:<br>
        <input type="button" value="1" name="no" onclick="moveNumbers()"> 
        <input type="button" value="2" name="no" onclick="moveNumbers()"> 
        <input type="button" value="3" name="no" onclick="moveNumbers()"> 

        <input type="text" id="result" size="20">
    </form>
</body>

</html>
like image 504
GRicks Avatar asked Dec 20 '12 20:12

GRicks


2 Answers

There are a few flaws here. It doesn't seem like option is defined. And you have no way to retrieve the button that was actually clicked.

What you can do is pass this.value to your onclick event handler. This passes the value of the button you push, and use that to append to your textbox value.

<script> function moveNumbers(num) {
    var txt=document.getElementById("result").value;
    txt=txt + num;
    document.getElementById("result").value=txt;
    }
</script>
Select numbers: <br> <input type="button" value="1" name="no" onclick="moveNumbers(this.value)">  
<input type="button" value="2" name="no" onclick="moveNumbers(this.value)">  
<input type="button" value="3" name="no" onclick="moveNumbers(this.value)">  
<input type="text" id="result" size="20">

http://jsfiddle.net/cMN44/

like image 139
Nick Rolando Avatar answered Nov 02 '22 20:11

Nick Rolando


Assuming you want the value of the button to be inserted into the text box:

<!DOCTYPE html>
<html>

<head>
    <script>
        function moveNumbers(number){
            document.getElementById("result").value=number;
        }
    </script>
</head>

<body>
    <form>
        Select numbers:<br>
        <input type="button" value="1" name="no" onclick="moveNumbers(this.value)"> 
        <input type="button" value="2" name="no" onclick="moveNumbers(this.value)"> 
        <input type="button" value="3" name="no" onclick="moveNumbers(this.value)"> 

        <input type="text" id="result" size="20">
    </form>
</body>

</html>
like image 30
Tim Booker Avatar answered Nov 02 '22 19:11

Tim Booker