Validate email on keyup and tab - javascript

I am success to handle user input on keyup but I have a problem to handle when the user press the tab key.
So this is my code so far:
var doneTypingInterval = 1000;
// Handle on keyup
$('#f-name').keyup(function() {
clearTimeout( typingTimer );
if($(this).val) {
typingTimer = setTimeout( doneTypingUsername, doneTypingInterval );
}
});
// Handle on tab-press
$('#f-name').on(function(e) {
var keyCode = e.keyCode || e.which;
clearTimeout( typingTimer );
if(keyCode == 9) {
e.preventDefault();
typingTimer = setTimeout( doneTypingUsername, doneTypingInterval );
}
});
// Error handler
function doneTypingUsername() {
if($('#f-name').val() == '') {
$('#f-name').siblings('.case1').fadeIn(500);
$('#f-name').siblings('.case2').hide();
valid_name_f = false;
} else {
if(!isValidUsername($('#f-name').val())) {
$('#f-name').siblings('.case1').hide();
$('#f-name').siblings('.case2').fadeIn(500);
valid_name_f = false;
} else {
$('#f-name').siblings('.case1').hide();
$('#f-name').siblings('.case2').hide();
valid_name_f = true;
set_name_timer = false;
}
}
checkForm();
}
As far as I run the code, it works fine. However, I think the way I handle the tab-press is not right. Since the keyup and tab-press will execute the same same thing, is there a better way to handle these two together?

Where your jquery says
$('#f-name').keyup(function() {
And
$('#f-name').on(function(e) {
You could be more efficient with
function functionName(e){
//do your timer and validation here
}
$(document).on('keyup', '#f-name', functionName(e));
$(document).on('blur', '#f-name', functionName(e));
Although this is not the cleanest solution, it should accomplish your email validation in both cases

Related

Disable enter keypad for 3 seconds after first press and re-enable the enter keypad again

This is my code but I am having challenges on how to go about it. I want to disable enter keypad for three seconds after the first press and re-enable it again. This is my attempt
function disableForThreeSeconds(e) {
if (e.keyCode == 13) {
//if pressed for the first disable for three seconds
}
}
}
Kindly assist!
In if block:
e.target.disabled = true;
window.setTimeout(function(){
e.target.disabled = false;
},3000);
You can use setTimeout. Look documentation here.
Api:
number setTimeout(function callback, integer milliseconds )
Simple jQuery example:
setTimeout(function(){
$(window).keypress(function(e){
if (e.keyCode == 13) {
return false;
}
})
}, 3000);
Instead of disabling the keypad you can just ignore the events in your handler...
var isDisabled;
function disableForThreeSeconds(e) {
if (e.keyCode == 13) {
if (!isDisabled) {
isDisabled = new Date();
} else {
//if pressed for the first disable for three seconds
if (new Date() - isDisabled > 3 * 1000 )
isDisabled = 0;
}
}
}

how to delay keypress enter

window.addEventListener('keydown', function(event) {
onKeyDownHandler(event);
}, false);
function onKeyDownHandler(e)
{
var focus_id = e.target.id;
switch (e.keyCode) {
case 13: // enter
if(focus_id == "Text1")
{
alert("function 1");
}else if(focus_id == "Text2")
{
alert("function 2");
}else if(focus_id == "Text3")
{
alert("function 3");
}
return;
}
}
is there anyway i can delay or make sure user dont spam by clicking the enter , how do i set keypress delay on my enter button ? which is the best way set delay timer or remove EventListener?
You can use the jQuery throttle/debounce plugin to only handle call your function when there is a pause in keyDown events.
You can prevent the default action for a period of time after the last Enter keypress:
window.addEventListener('keydown', onKeyDownHandler, false);
var lastEnter = null;
function onKeyDownHandler(e) {
var focus_id = e.target.id;
switch (e.which || e.keyCode) { // Note the e.which, for x-browser compat
case 13:
if (lastEnter && Date.now() - lastEnter < 5000) {
e.preventDefault();
return;
}
lastEnter = Date.now();
// Enter key processing...
break;
// ...other keys...
}
}
Or using jQuery (you've tagged your question jquery, but don't appear to be using jQuery in your code):
$(window).on("keydown", function(e) {
onKeyDownHandler(e);
});
var lastEnter = null;
function onKeyDownHandler(e) {
var focus_id = e.target.id;
switch (e.which) { // jQuery normalizes this for you
case 13:
if (lastEnter && Date.now() - lastEnter < 5000) {
e.preventDefault();
return;
}
lastEnter = Date.now();
// Enter key processing...
break;
// ...other keys...
}
}
Side notes:
Since the return value of an addEventListener callback is completely ignored and addEventListener calls the handler with just a single argument, if you're not using this within the handler (as you appear not to be), there's no need to wrap a function around onKeyDownHandler; just use it directly.
Some browsers use which for the keycode, others use keyCode, which is why I used e.which || e.keyCode in the switch. JavaScript's curiously-powerful || operator will use e.which if it's not falsey, e.keyCode otherwise.
You can create a timeout on enter press, and on another enter press, overwrite that previous timeout with the new one. That means that if you for example press enter again before the first timeout has ended, that first timeout will be overwritten by a new one, so that you get a new x amount of time before the actual timeout is executed. This works until infinity.
Example:
var keyup_timeout;
var timeout_delay_in_ms = 500;
element.on('keyup', function(e) {
e.preventDefault(); // Prevent default enter press action.
var enter_pressed;
if (e.which === 13) {
enter_pressed = true; // Just an example to illustrate what you could do.
}
if (enter_pressed) {
clearTimeout(keyup_timeout); // Clear the previous timeout so that it won't be executed any more. It will be overwritten by a new one below.
keyup_timeout = setTimeout(function() {
// Perform your magic here.
}, timeout_delay_in_ms);
}
});

Check which button clicked on page leave prompt?

So I have this code and I'm trying to find out how to check which button the user clicks on the prompt. I'd like to fire an event if they click stay or fire a different event if they leave. Is this possible?
var submitted = false;
$(document).ready(function () {
window.onbeforeunload = function (e) {
if (!submitted) {
var message = "Are you sure you want to leave?", e = e || window.event;
if (e) {
e.returnValue = message;
}
return message;
}
}
$("form").submit(function() {
submitted = true;
});
});
Actually there is no way to find that which button is clicked(in case of onbeforeunload confirm box) according to my knowledge.
But we can achieve the required functionality by following way:
window.onbeforeunload = function (e) {
if( $("table tbody.files tr.template-download.fade").length > 0 )
{
var message = "XYZ",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
}
}
And you can write the code for 'yes' button click inside following:
$( window ).unload(function() {
//--> Here
});
use Javascript "confirm" for that:
if(confirm("Are you sure you want to leave?"))
{
//True part
}
else
{
//False part
}

JS: How to detect whether cursor is in textfield

I want to use some letters ( keys ) as shortcut for some actions in javascript. I want to check whether the cursor is focused on any textfield, form input, etc. so that the shortcut action will be canceled when user is typing something in a form or textfield.
For example, i want an alert() to be executed when user presses 'A'. But if the user is typing some text in a textarea like 'A website' then he will be pressing 'A', this time alert() should not be executed.
$(document).keydown( function( e ) {
if( e.target.nodeName == "INPUT" || e.target.nodeName == "TEXTAREA" ) return;
if( e.target.isContentEditable ) return;
// Do stuff
}
window.onkeydown = function(e){
if ( e.target.nodeName == 'INPUT' ) return;
handle_shortcut();
};
jQuery
$(window).bind('keydown',function(e){
if(e.target.nodeName.toLowerCase() === 'input'){
return;
}
alert('a');
});
or pure js
window.onkeydown = function(e){
if(e.target.nodeName.toLowerCase() === 'input'){
return;
}
alert('a');
};
What you can do in addition to this is define an array of non-alert element types, so input, textarea etc and then check none of those elements are currently the target.
Demo: http://jsfiddle.net/7F3JH/
You can bind and unbind the shortcut events depending on which element currently has focus on your page.
JavaScript
window.onload = initWindow();
function initWindow () {
attachShortcutHandler();
var inputs = document.getElementsByTagName('input');
for (var i = 0, max = inputs.length; i < max; i++) {
inputs[i].onfocus = removeShortcutHandler;
intputs[i].onblur = attachShortcutHandler;
}
}
function removeShortcutHandler () {
window.onkeypress = null;
}
function attachShortcutHandler() {
window.onkeypress = function () {
//your code here
}
}
jQuery
$(function () {
initShortcutHandler();
$('input, [any other element you want]')
.on('focus', function () {
$('body').off('keypress');
})
.on('blur', function () {
initShortcutHandler();
});
});
function initShortcutHandler() {
$('body').on('keypress', function () {
//do your stuff
});
}
jQuery mouseover()
$('element').mouseover(function() {
alert('over');
});
you need to make a flag as global. and set it false when any textbox has focus.
var flag = true;
$('input:type="text").focus(function(txt) {
flag= false; });
if(flag) //shortcut keys works...
Better use the focusOut method defined in JQuery. As per my understanding you can do something like this
$("input").focusout(function() {
if($(this).val() == "A"{
alert("your message");
return false;
}else{
//do other processing here.
}
});
Hope this helps :)

JavaScript execute until keypress

I want to execute a loop/action until a key is pressed and onpress I want to stop that action and call the function getKey. Can anybody suggest how to do this?
function getKey(e)
{
var pressedKey;
if (document.all) { e = window.event; }
if (document.layers || e.which) { pressedKey = e.which; }
pressedCharacter = String.fromCharCode(pressedKey).toLowerCase();
move(pressedCharacter);
}
document.onkeypress = getKey;
I want the move() function to be executing continuously till a key is not pressed . if it's pressed i want to re-execute the move() function with the new pressed character
Depends on how you loop. The easiest way is with an interval:
var interval = window.setInterval(function () {
// do your thing, do your thing
}, 1000);
document.onkeypress = function () {
if (/* some specific character was pressed */) {
window.clearInterval(interval);
// do some other thing, other thing
}
};
Use http://www.asquare.net/javascript/tests/KeyCode.html to find keycodes
<script>
document.onkeyup = getKey;
function getKey() {
// If the users hits 'a', stop loopcode from running.
if(event.keyCode == 65){
window.clearInterval(interval);
};
}
var interval = setInterval(function() {
// loopcode here
}, 1000);
</script>

Categories