Catch HTML Form "Enter" Press to execute AJAX, not Post

Viewed 37

i am currently working on a HTML Form (building it with the pug view engine), that I try to work with in an ajax request after fill-out.

When pressing Enter after editing my input-element, it seems to submit the form (post request i suppose?). I would like to the enter-press event to (just like my button) fire a jquery function instead.

The form is build as following:

form(class="form" action="")
  div(class="form-group")
    label(for="testid") Tickersymbol
    input(name="symbol", type="text", class="form-control", id="testid", placeholder="Please enter the symbol")
   div(class = "form-group")
     button(class="btn btn-primary" id="getdata" type="button") Get Info

Current JQuery Code:

// This does not work
$("#inputStocksymbol").trigger('click', function (){
    console.log("Enter event should have happened.")
})

// This does work
$("#getquote").click( function () {
    console.log("Button has been pressed")
})

Are there any suggestions on how this would be possible?

Thanks!

1 Answers

The Return keypress within an input of a form will, by default, submit that form. Therefore, if you want to run some logic when this occurs hook to the submit event:

$("form.form").on('submit', function(e) {
  e.preventDefault()

  // run your code here

  console.log("Button has been pressed");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form" action="">
  <div class="form-group">
    <label for="testid">Tickersymbol</label>
    <input name="symbol" type="text" class="form-control" id="testid" placeholder="Please enter the symbol" />
    <div class="form-group">
      <button class="btn btn-primary" id="getdata" type="button">Get data</button>
    </div>
  </div>
</form>

Alternatively, if you just want to run some code when Return is pressed within the input, but do not allow the keypress to submit the form, you can hook a keypress event handler directly to the input, making sure to call stopPropagation():

$("#testid").on('keypress', e => {
  if (e.keyCode === 13) {
    e.preventDefault();
    e.stopPropagation();
    
    // run your code here
    
    console.log("Return has been pressed");
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="form" action="">
  <div class="form-group">
    <label for="testid">Tickersymbol</label>
    <input name="symbol" type="text" class="form-control" id="testid" placeholder="Please enter the symbol" />
    <div class="form-group">
      <button class="btn btn-primary" id="getdata" type="button">Get data</button>
    </div>
  </div>
</form>

Related