Reputation: 2534
I have this simple sctipt
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(function(){
$("#message").keypress(function(e){
var code = (e.keyCode ? e.keyCode : e.which);
if (code == 13){
$("#query").submit();
}
});
});
</script>
and this html:
<div id="textarea">
<form name="query" class="form1" id="query" action="query.py" method="post">
<textarea rows="2" name="message" id="message" class="message" placeholder="RM911 Chat" cols="26"></textarea>
<input type="submit" id="submit" name="submit1" value="a"/>
</form>
</div>
if input's id is "submit" nothing works, if it's id is something else - it works... But the whole project uses "submit" id for submit buttons, and I don't want to rename it (because of CSS). Is there anything I can do?
Upvotes: 4
Views: 11149
Reputation: 40639
Try this, in your script,
$("#submit").trigger('click');
Full Code,
$(function () {
$("#message").keypress(function (e) {
var code = (e.keyCode ? e.keyCode : e.which);
//alert(code);
if (code == 13) {
$("#submit").trigger('click');
return true;
}
});
});
Upvotes: 13
Reputation: 13517
Here you go, this submits the form (by triggering the submit button) when the enter key is pressed; and lets you create a new line when you hold Control and press Enter.
$(function(){
function getCaret(el) {
if (el.selectionStart) {
return el.selectionStart;
} else if (document.selection) {
el.focus();
var r = document.selection.createRange();
if (r == null) {
return 0;
}
var re = el.createTextRange(),
rc = re.duplicate();
re.moveToBookmark(r.getBookmark());
rc.setEndPoint('EndToStart', re);
return rc.text.length;
}
return 0;
}
$("#message").keyup(function(e){
if ((e.keyCode == 13 || e.keyCode == 10) && e.ctrlKey) {
var content = $(this).val();
var caret = getCaret(this);
$(this).val(content.substring(0,caret)+
"\n"+content.substring(caret,content.length));
e.stopPropagation();
} else if (e.keyCode == 13 || e.keyCode == 10){
$("#submit").click();
}
});
});
Here's a Demo
Credit to TheSuperTramp for the getCaret
and original keyup code for the Ctrl+Enter solution.
Upvotes: 3