szammyboi
szammyboi

Reputation: 45

Use an enter key to perform a text field function

My Code that I tried to use. Please tell me what I have done wrong. I am not very good at JavaScript so, don't judge.

<!-- Textfield with Floating Label -->

<form action="#">
  <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
    <input class="mdl-textfield__input" type="text" id="userInput" onkeypress="handle(e)">
    <label class="mdl-textfield__label" for="userInput">Answer Here</label>
  </div>
</form>

<script>
    function handle(e){
        if(e.keyCode === 13){
            e.preventDefault(); // Ensure it is only this code that rusn
var input = document.getElementById("userInput").value;
    alert(input);
        }
    }
</script>
    </body>
</html>

Upvotes: 0

Views: 965

Answers (1)

adeneo
adeneo

Reputation: 318352

You probably wanted to pass the event, not just e

<input class="mdl-textfield__input" type="text" id="userInput" onkeypress="handle(event)">

<form action="#">
    <div class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
        <input class="mdl-textfield__input" type="text" id="userInput" onkeypress="handle(event)">
        <label class="mdl-textfield__label" for="userInput">Answer Here</label>
    </div>
</form>

<script>
    function handle(e) {
        if (e.keyCode === 13) {
            e.preventDefault(); // Ensure it is only this code that rusn
            var input = document.getElementById("userInput").value;
            alert(input);
        }
    }
</script>

Preferably you'd use addEventListener instead

document.getElementById('userInput').addEventListener('keypress', function(e) {
    if(e.keyCode === 13) {
        e.preventDefault();
        var input = this.value;
        alert(input);
    }
});

Upvotes: 1

Related Questions