Reputation: 47
I want to submit the content in the textarea as shown below by just hitting the Enter
key on any keyboard on planet earth. When the user hits the Shift+Enter
key, the caret has to go to a new line and on hitting Enter
the submitted textarea content should have the new lines created when the Shift+Enter
was pressed. The content of the textarea should be inserted after the the div with class commentWrap
but the last submitted comment should apear last and vice verser.
I want this solution to work in all browsers.
<div class="commentWrap"></div>
<textarea id="test"></textarea>
<script type="text/javascript">
$(document).ready(function() {
$("#test").keypress(function(e) {
var textVal = $(this).val();
if(e.which == 13 && e.shiftKey) {
//What should I really do here
}
else if (e.which == 13 && ! e.shiftKey) {
e.preventDefault(); //Stops enter from creating a new line
//this.form.submit(); //or ajax submit
if (this.value ==="") {
alert("Hey punk! Put some text before you hit enter.");
}else {
alert(textVal);
$("<div class='comment'>"+ textVal +"</div>").insertAfter('.commentWrap');
}
}
});
});
</script>
Upvotes: 0
Views: 356
Reputation: 3431
if you already have a submit button that is used to submit the form you can simply trigger the click handler.
$("#submitButton").click();
Upvotes: 0
Reputation: 39320
//What should I really do here
Nothing I think, all browsers will insert a new line if shift + enter was pressed so you can just return true;
Upvotes: 1