Reputation: 305
In the script below I've got the code to allow me to add a new line by pressing shift+enter but when I just press enter the code does nothing. I also get no errors. I've removed the resize caret so there is no need to mess with that. What is the bug in my code keeping me from submitting the form?
Disclaimer: yes I know there are multiple posts on this subject but none of them fix my problem so I'm hoping it's a new problem.
<script>
$('#myFormActivity .commentTextarea').keypress(function(event){
if (event.keyCode==13 && !event.shiftKey) {
event.preventDefault();
$( "#myFormActivity" ).submit(function(event1) {
alert("sent");
// Stop form from submitting normally
event1.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
activityid = $form.find( "input[name='activityid']" ).val(),
comment = $form.find( "textarea[name='comment']" ).val(),
url = "process/insertComment.php";
// Send the data using post
var posting = $.post( url, { activityid: activityid, comment: comment } );
// Put the results in a div
posting.done(function( data ) {
$(this).children('.commentTextarea').val('');
});
return false;
});
return false;
}
});
</script>
The class commentTextarea is the class assigned to the textarea element inside of the form which has the ID of myFormActivity.
Upvotes: 0
Views: 183
Reputation: 6733
What you are doing in your keypress event when you say
$( "#myFormActivity" ).submit(function(event1) {
is binding an event to the form submit, not triggering it. Something like (I haven't actually tested it) the following is more what you want I think (note the mime-type on the script tag and that the events should be bound in a document ready):
<script type="text/javascript">
$(function(){
$('#myFormActivity .commentTextarea').keypress(function(event){
if (event.keyCode==13 && !event.shiftKey) {
event.preventDefault();
$( "#myFormActivity" ).submit();
return false;
}
});
$( "#myFormActivity" ).submit(function(event1) {
alert("sent");
// Stop form from submitting normally
event1.preventDefault();
// Get some values from elements on the page:
var $form = $( this ),
activityid = $form.find( "input[name='activityid']" ).val(),
comment = $form.find( "textarea[name='comment']" ).val(),
url = "process/insertComment.php";
// Send the data using post
var posting = $.post( url, { activityid: activityid, comment: comment } );
// Put the results in a div
posting.done(function( data ) {
$(this).children('.commentTextarea').val('');
});
return false;
});
});
</script>
Upvotes: 2