0

I want to submit a form with keyboard from the following codes:

<form class="article-footnote-form footnote-form" style="margin-top:10px" >
<div class="form-group row">
    <div class="col-md-9">
        <textarea class="form-control" name="footnote" rows="3" autofocus></textarea>
    </div>
    <div class="col-md-3">
        <button class="btn btn-primary" type="submit" id="articleFootnoteBtn">Add Annotation</button>
    </div>
</div>
</form>

I employed the .submit() shortcut to submit and desire to take advantage of its implicit keypress to submit

 $(".article-footnote-form").submit(function(e){
    e.preventDefault();

Unfortunately, it did not work, I have to click to submit.

I found a good solution in Enter to submit shift+enter to feedline

$("#textareaId").keypress(function (e) {
    if(e.which == 13 && !e.shiftKey) {        
        $(this).closest("form").submit();
        e.preventDefault();
        return false;
    }
});

However, when changed the triggering event, I should updated bulks of codes depending on the previous.

Could make $("form").submit() working on textarea just it does on input type="text"?

AbstProcDo
  • 19,953
  • 19
  • 81
  • 138

1 Answers1

1

You can check if the keycode is 13 (enter key) and that the key is not Shift to submit the form.

Note: You should prevent the default action before you submit the form, not after.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="article-footnote-form footnote-form" style="margin-top:10px" id="footnoteForm">
<div class="form-group row">
    <div class="col-md-9">
        <textarea class="form-control" name="footnote" rows="3" autofocus></textarea>
    </div>
    <div class="col-md-3">
        <button class="btn btn-primary" type="submit" id="articleFootnoteBtn">Add Annotation</button>
    </div>
</div>
</form>
<script>
$("textarea").keypress(function(e){
  if(e.which==13 && !e.shiftKey){
    e.preventDefault();
    $('#footnoteForm').submit();
  }
});
$("#footnoteForm").submit(function(e){
  alert("Submitting form!");
});
</script>