Lenny
Lenny

Reputation: 456

Submit form on keypress in textarea

I've been trying to do something as basic as submitting a textarea on enter (and shift+enter), and it's really making me confused – I've consulted previous topics on here on Stackoverflow in this matter but no previous solution seem to do the trick. Shouldn't $('#form').submit(); do the job? Neither this.form.submit(); or document.getElementById("form").submit(); seems to provide a solution either, though I could have messed something up at this point.

I've created a jsFiddle in order to try it out. Most likely it's a very fundamental mistake that I'll be embarrassed about, but sadly I've spent so much time with it that I can't look at it with fresh eyes anymore.

<form id="form" name="form" method="post">
    <textarea id="contentsubmit" name="contentsubmit" class="no-formatting contentsubmit" type="text" placeholder="textfield for submitting textcontent"></textarea>
    <input id="submit" type="submit" name="submit" value="Send" />
</form> 

<script>
$(document).ready(function(){
    $('#contentsubmit').keypress(function(e) {
      if(e.which == 13) {
           $('#form').submit();
           // this.form.submit(); 
           // document.getElementById("form").submit(); 

           console.log('log me!');
           e.preventDefault(); // Stops enter from creating a new line
       }
    });
});
</script>

Upvotes: 0

Views: 1058

Answers (1)

epascarello
epascarello

Reputation: 207547

You need to rename your submit button, you are overridding the submit method.

Change

<input id="submit" type="submit" name="submit" value="Send" />

to

<input id="btnSubmit" type="submit" name="btnSubmit" value="Send" />

and change

$('#form').submit();

to

$('#form')[0].submit();

or

$('#form').get(0).submit();

Upvotes: 1

Related Questions