Search code examples
htmlsearchonkeydown

How to trigger click event when pressing enter key? Text area


I have search area which works fine as I need it to but the problem is when i hit enter it won't search for results, so you need to press button to do so. I tried different codes but nothing is working and I'm wondering if anyone has solution for it. This is code that I have:

<input 
 data-path=".title" 
 data-button="#title-search-button"
 type="text"
 value=""
 placeholder="Search..."
 data-control-type="textbox"
 data-control-name="title-filter"
 data-control-action="filter"
/>

I guess this could work with "onkeydown=" but not really sure what to add after it.

I would really appreciate if someone has solution for this.


Solution

  • Although you can use the onkeydown attribute I prefer to do these things through JavaScript event listeners & handlers. If you want to do this with the onkeydown attribute then look at Bryan's answer.

    I would first add an ID/Class name to the input so we can easily target it. In my example i will add searchTextas the ID for this input.

    JavaScript:

    document.getElementById('searchText').addEventListener("keydown",function(e){
      if(e.keyCode == 13){
       //doSomething()
      } 
    });
    

    jQuery:

    $('#searchText').on('keydown',function(e){
      if(e.which == '13'){
        //doSomething();
      } 
    });