I am having some problems with executing a function depending on whether the 'blur' or 'keydown' event is triggered.
I am having the following situation:
$(document).ready(function() {
function blurChange(e) {
clearTimeout(blurChange.timeout);
blurChange.timeout = setTimeout(function() {
var keycode = (e.keyCode ? e.keyCode : e.which);
var entered_date = $('.format').val().split('-');
if (entered_date[2].length == '4' && (entered_date[1].length == '2' || entered_date[1].length == '1') && (entered_date[0].length == '2' || entered_date[0].length == '1')) {
console.log("yes");
$('.formatted-date').off('blur change');
} else {
$('.error').html("error");
}
}, 10);
}
$('.format').on('blur keydown', blurChange);
});
HTML:
<input class="format" value="01-02-2099">
<span class="error"></span>
The situation that I am seeking for is to have an input field where a user can fill any date in the given format and when the input lost his focus the console.log is triggered. I also want that this console.log is triggered when pressing the 'enter' button (event code 13).
In short,
I want to have two situations working:
Situation 1: The input is checked with the if statement if the user is blurring (unfocus)
Situation 2: The input is checked with the if statement if the user press enter within the input field.
So in both situations(blur, onkeyenter) the input should be checked. I hope that I made myself clear. For any questions please ask.
DEMO HERE: JSFIDDLE
Not changing your code too much, you could simply do:
if((e.type == "keydown" && keycode == 13)
|| e.type == "blur")
Before your current if statement.
JsFiddle
Although it may make more sense to separate them like here:
Possible better way
I've also added this $('.error').html(""); so the error message clears when data is correct.
Related
I am trying to build a comment section that allows instant preview on the front end.
Everything worked fine except the behavior after submitting the comment.
In my code, I trigger the submission of the comment when the user press the Enter key in the textarea, then clear the textarea by resetting the value.
However, even after I disabled the default behavior of the enter key by declaring e.preventDefault(), a new line is still inserted when enter is pressed repeatedly.
Also, even after I check the length of the value of the textarea before submitting, my code accept comment with only / '\n' as valid content and hence the user will be able to submit 'empty' comment if they press enter in the textarea multiple times...
Please help, I cannot think of a solution and I am considering to add a post button where the user has to manually click it to submit...
My code on fiddle:
http://jsfiddle.net/8ve0gLab/2/
My code:
$(document).ready(function(){
$('#comment-input').keydown(function(e){
var commentContent = $(this).val()
if (e.which == 13) {e.preventDefault()}
if (e.which == 13) {
e.preventDefault()
if (commentContent.length != 0) {
$('#comment').append(commentContent)
$(this).val('')
}
else {
alert('Comment is empty')} /*This line is not working properly*/
}
})
})
Try change your code to
$(document).ready(function(){
$('#comment-input').keydown(function(e){
var commentContent = $(this).val();
if (e.which == 13) {
if (commentContent.trim()){
$('#container').append("<p>"+commentContent+"</p>");
$(this).val('');
}
else {alert('Area is empty');}
}
})
})
notice the ".trim()" which is a javascript string method.
you can try in the jsfiddle here : http://jsfiddle.net/xdxqwLof/
This may address your issue:
if (event.keyCode == 10 || event.keyCode == 13){
event.preventDefault();
}
JS Fiddle Demo
I'm trying to implement a form with multiple buttons on it. When I press enter I want to have my default button submitted. This code from http://greatwebguy.com/programming/dom/default-html-button-submit-on-enter-with-jquery/ generally works:
$(function() {
$("form input").keypress(function (e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
$('button[type=submit].default').click();
return false;
} else {
return true;
}
});
});
but...
when I type in input field I have an autocomplete popup so when I press enter in this popup I expect to put this value to input field, not submit all form. Can I check somehow if this enter comes from popup? Or I should try to do this different way?
EDIT:
I think I didn't say it clear. This popup is not any part of jquery. It's standard popup that shows previously typed data into input. So it hasn't got any class nor id. Stop propagation doesn't work either. None of solutions below resolve this problem
You could use :visible to see if the dropdown div for the autocomplete is open, and then prevent the enter key action of your code completing. Something like this:
$("form input").keypress(function(e) {
var key = e.which || e.keyCode;
if (key == 13 && !$(".autocomplete").is(":visible")) {
e.preventDefault();
$('form').submit();
}
});
You could also use event.stopPropagation() on the enter key press in the autocomplete function, however you'll probably have to amend the source manually which isn't ideal.
Before return false;
write
e.preventDefault();
or/and
e.stopPropagation();
$("form input").keypress(function (e) {
if (e.target.id !== "autoCompliteId" && ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13))) {
$('button[type=submit].default').click();
return false;
} else {
return true;
}
});
I modified my code and it works now.
I have an enum called Operation in my command and I set different value of the field before every submit button eg:
<input type="submit" value="do sth" onclick="setOperationAndSubmit('DO_STH')"/>
<input type="submit" value="next" onclick="setOperationAndSubmit('DEFAULT')"/>
function setOperationAndSubmit(operation) {
if (document.myForm.elements['operation'].value === '') {
document.myForm.elements['operation'].value = operation;
}
document.myForm.submit();
}
Then I have my action that listens to keypress and it set appropriate operation on every enter key:
$(function() {
$("form input").keypress(function(e) {
if ((e.which && e.which == 13) || (e.keyCode && e.keyCode == 13)) {
document.myForm.elements['operation'].value = 'DEFAULT';
}
});
});
so default action is executed when I press enter
I have a textbox with a keydown handler. The handler detects if you press escape and if so it is meant to clear the textbox value. However, calling tb.value = "" normally works, unless the textbox has focus in which case it does nothing. I suspect I have to select the text and delete it, but how? This is in Firefox 12.
Have a look at this:-
LIVE DEMO
HTML:
<input type="text" id="content" />
JS:
$(document).keyup(function(e) {
if (document.activeElement.nodeName == 'INPUT')
{
if (e.keyCode == 13) { // Enter
alert('Enter Key Up');
}
if (e.keyCode == 27) { // Esc
alert('Esc Key Up');
$('#content').val("");
}
}
});
Basically sometimes I need to show a form that is pre-populated with a record. Depending on the users privileges, he may or may not be able to edit the data.
The problem I'm encountering is that sometimes a user will try to edit a textbox that's been disabled by clicking on it and hitting the "backspace" button to edit the text. This causes the browser to go back one page... Annoying.
If it's asp .net you can simply do it like this:
<script language=javascript>
function cancelBack()
{
if ((event.keyCode == 8 ||
(event.keyCode == 37 && event.altKey) ||
(event.keyCode == 39 && event.altKey))
&&
(event.srcElement.form == null || event.srcElement.isTextEdit == false)
)
{
event.cancelBubble = true;
event.returnValue = false;
}
}
</script>
<body onkeydown=cancelBack()>
You need to catch the keyboard event in javascript and stop it from executing. What server-side code you are using (ASP.NET) doesn't make a difference.
window.onkeydown = function(event) {
if(event.keyCode == 8)
return false;
}
Just tested in Chrome and it seems to work
Place this under in the document ready function if you have one
window.onkeydown = function (event)
{
if (event.keyCode == 8) {
return false;
}
}
okay so I have the hotkey working just can't make it stop
$(document).keypress(function(e){
if(e.which == 13){
//Enter key is press do what you want
}
else if(e.which == 67 || e.which == 99){
//C key is press do what you want
window.location.href = "/html/credits.php";
}
else if(e.which == 32){
alert("Space pressed");
}
});
$("input.registerform").keypress(function(e){
e.stopPropagation(); });
Here is what I have to make it stop, the class of my input form is "registerform bgcolor2" but it wont work with either "input.registerform" neither with "input.registerform bgcolor2" I tried adding an ID to it with registerform as ID didn't work either :/
Is it being caused my AJAX? or am I missing something here?
(Sorry I reposted this just made a new account and cant find my old question back >.<)
I understand, that since you attach your event listener to the document object, all input accepting elements, such as textfields, selects, etc. will handle hotkeys, hence lose their normal behavior.
Take a look at line 44 in the jquery.hotkeys plugin. It excludes all input-accepting elements on initialization.
P.S. Maybe this plugin is useful as a whole for your task.
The key is to check, whether an event comes from a text-accepting input.
# only bind event to text-accepting elements, if they have been
# explicitly selected
# if your event variable happens to be called e, please adjust accordingly
if ( this !== event.target &&
( /textarea|select/i.test( event.target.nodeName ) ||
event.target.type === "text") ) {
return;
}
As your code stands now, you would need to insert this snippet at the beginning of the anonymous function, you bind to the keypress event.
Seems to be working just fine :)
example:
First example: http://jsfiddle.net/HenryGarle/SG5Um/
Second example: http://jsfiddle.net/HenryGarle/SG5Um/1/
New code:
$(document).keypress(function(e){
if(e.which == 13){
alert("Enter");
}
else if(e.which == 67 || e.which == 99){
alert("c");
//window.location = 'whateveryouwant';
}
else if(e.which == 32){
alert("Space pressed");
}
});
$("input.registerform.bgcolor2").live('keypress', function(e){
alert("Stopped");
e.stopPropagation();
});
Stops:
<input class="registerform bgcolor2" type="text">
<br>
Does not stop:
<input class="registerform" type="text">
Using this anything with ONLY registerform will act as normal but if it ALSO has bgcolor2 it will stop the event.