Edgar P-Yan
Edgar P-Yan

Reputation: 319

Change element value on onkeypress event in JavaScript

Please help me with my script. I don't understand why it does not work:

<html>
<body>
<input type="text" id="input" onkeypress="myFunction()">
<input type="button" value="Hallo" id="but">
<script>
function myFunction{
    document.getElementById('but').value = "changed";
}
</script>
</body>
</html>

Upvotes: 0

Views: 2279

Answers (2)

Sadhon
Sadhon

Reputation: 694

Very simple you have forgotten to place parantheses after myFunction.

your code should be:

 <script>
function myFunction(){
    document.getElementById('but').value = "changed";
}
</script>

Upvotes: 2

stefan bachert
stefan bachert

Reputation: 9624

This way it work. Function needs parenthesis

    function myFunction() {
        document.getElementById('but').value = "changed";
    }
<html>
    <body>
    <input type="text" id="input" onkeypress="myFunction()">
    <input type="button" value="Hallo" id="but">

    </body>
    </html>

an alternative way is

    myFunction = function () {
        document.getElementById('but').value = "changed";
    }

Upvotes: 1

Related Questions