Home > Mobile >  Want to make input box in JS clear when enter is clicked
Want to make input box in JS clear when enter is clicked

Time:04-05

I am trying to make an input text box clear when enter is inputted using JS.

This is what I have so far (I don't know what kind of eventlistner I'd use to make it so when enter is clicked, it performs the action):

<!DOCTYPE html>

<html>
    <body>
        <center>
            <input id="text_box" type="text">
            <script>
                var box = document.getElementById("text_box");

                document.addEventListener("keyup", function(e) {
                    if (e.which == 13) {
                        box = "";
                    }
                })
            </script>
        </center>
    </body>
</html>

I'm really new to this kind of programming, so any help would be appreciated. Thank you.

CodePudding user response:

document.addEventListener("keyup", function(e) {
    if (e.which == 13) {
        // box = '';
       box.value = ''
    }
})

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/Input

CodePudding user response:

You can approach this in two different ways, first is you can just wrap the input with a form tag and prevent the form from performing default event(like submitting to another page or self)

Secondly you can use the keypress event to listen to the button click and when the user press enter you will clear the input value.

    <input id="demo">
    <script>
     var demo = document.getElementById("demo"); 
demo.addEventListener("keypress", function(e) {
        if (e.which == 13) {         
        demo.value = '' 
      }}) 
    </script> 
  • Related