JQuery .focus() not work in .blur() event in Firefox - javascript

i have used below code but it not work in firefox for focus textbox in .blur() event using JQuery
$("#txtfname").focus(function () {
if ($("#txtfname").val() == "" && $("#txtfname").val().length >= 2) {
$("#fnamemsg").hide();
}
});
$("#txtfname").blur(function () {
if ($("#txtfname").val() != "" && $("#txtfname").val().length < 2) {
$("#fnamemsg").show();
$("#fnamemsg").html("Minimum 5 character");
$("#txtfname").focus();
}
else { $("#fnamemsg").hide(); }
});

Your conditions are messed up and your message doesn't match your conditions either.
The following will hide the message on focus if the value of #txtfname is 5 or more characters and show the message on blur if its less than 5 characters.
$("#txtfname").focus(function () {
if ($("#txtfname").val().length >= 5) {
$("#fnamemsg").hide();
}
});
$("#txtfname").blur(function () {
if ($("#txtfname").val().length < 5) {
$("#fnamemsg").show();
$("#fnamemsg").html("Minimum 5 characters");
$("#txtfname").focus();
}
else { $("#fnamemsg").hide(); }
});

$("#txtfname").focus(function () {
//Check if value is blank or not
if ($("#txtfname").val() === "" && $("#txtfname").val().length >= 2) {
$("#fnamemsg").hide(); // Hide message
}
});
var element = document.getElementById('txtfname');
element.focus();
element.onblur = function () {
if (element.value !== "" && element.value.length < 2) {
$("#fnamemsg").show();
$("#fnamemsg").html("* Firstname required 2 character");
setTimeout(function () {
element.focus();
}, 0);
} else {
$("#fnamemsg").hide();
}
};

Related

Show a div only when a value = 0

I have a problem with this script.
The script shows to me the hidden div #regalo if #total is between 99.99 and 299.99 ... ok, but (now), I also need to show the hidden div #alert when #total is 0 (zero), and be available to show if values ​​of #total more than 1 , and only when the screen is in landscapeand mode...
Truth is that I can't find a way to modify the code.
Any ideas?
$(document).ready(function() {
function manageRegalo() {
var totalStorage = Number(localStorage.getItem("total"));
var total = parseFloat($("#total").val());
if (totalStorage != null && total === 0) {
total = totalStorage;
}
if(total > 99.99 && total < 299.99) {
console.log("PASS");
$('#regalo').show();
//if(total === 0) {
//if(total == 0) {
//if(total < 1) {
//$('#alert').hide();
//}
//else{
//$('#alert').show();
//};
if (localStorage.getItem('suppress_gift_tooltip_1') == null) {
$('.tooltip').show();
window.setTimeout(function() {
$('.tooltip').fadeOut('slow');
}, 9000);
//--------------------
if (!$("#notify")[0].paused) { //play audio
$("#notify")[0].pause(); //play audio
$("#notify")[0].currentTime = 0; //play audio
} else { // play audio
setTimeout(function() { //play audio
$("#notify")[0].play(); //play audio
})}; //play audio
//--------------------
localStorage.setItem('suppress_gift_tooltip_1', 'true')
}
} else {
console.log("FAIL");
$('#regalo').hide();
}
}
$(document).on('click', function(event) {
const target = event.target;
if (target.matches('.comp-clone') || target.matches('.bbp')) {
manageRegalo();
localStorage.setItem('total', Number($("#total").val()));
}
});
manageRegalo();
});
#alert {
display: none
}
#media screen and (max-width:999px) and (orientation:landscape) {
#alert {
display: block !important
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<div id="regalo"></div>
<div id="alert"></div>
<!-- I need to show this div when the #total equals zero -->
This is where consistent and sensible indentation is important. All of the conditions you're trying are all valid:
if (total === 0)
if (total == 0)
if (total < 1)
Any one of them by itself will work just fine. But the problem is that they're not by themselves. They're inside another condition:
if (total > 99.99 && total < 299.99)
When that condition is true, none of your above conditions can possibly be true. The same variable (total) can not be greater than 99.99 and equal to 0 at the same time.
Don't put the test for zero inside of that if block:
if (total > 99.99 && total < 299.99) {
if (total === 0) {
//...
}
}
Put it outside of that if block:
if (total > 99.99 && total < 299.99) {
//...
}
if (total === 0) {
//...
}
Have a try with this
function manageRegalo() {
var totalStorage = Number(localStorage.getItem("total")) || 0;
var total = parseFloat($("#total").val());
if (totalStorage && total === 0) {
total = totalStorage;
}
$('#regalo').toggle(total > 99.99 && total < 299.99);
$("#alert").toggle(!total);
if ($('#regalo').is(":visible") && localStorage.getItem('suppress_gift_tooltip_1')!="true") {
$('.tooltip').show();
localStorage.setItem('suppress_gift_tooltip_1',"true");
window.setTimeout(function() {
$('.tooltip').fadeOut('slow');
}, 9000);
}
}

Can you nest on click events?

I'm making a pomodoro clock with a break timer and a session timer. I'm using a single numpad to input the data into each clock by trying to nest the o'clock event to set each clock. To make it happen you click the display for the clock and then start inputting the buttons. There is 0-9 a delete button and an enter button. I haven't been able to get it to even display anything for either function. So I'm starting to wonder if what I'm trying to do would even work? Just looking for whether you can nest on click events and if so what I'm doing wrong. Or another method for what I'm looking to do. Made a fiddle to view it minimize the js and css windows. https://jsfiddle.net/zackluckyf/jhe98j05/1/
$(".session-time-clock").click(function(){
// changes the color to make it flash, add a duration and then change it back
$(".num-button").css("background-color", "#BCC6CC");
function myFunction() {
myVar = setTimeout(changeBackground, 500);
}
function changeBackground() {
$(".num-button").css("background-color", "#575e62");
}
myFunction();
sessionTimeClock = "00:00";
counter = 4;
/*
Will this work?
*/
$("button").click(function(){
// gets button text label
var input = $(this).text();
// if, else if chain for calculator functions
if(input !== "Start" && input !== "Pause" && input !== "Reset" && input !== "X" && input !== "Enter" && counter > -1)
{
if(counter === 4)
{
sessionTimeClock = sessionTimeClock.slice(0,counter-1) + input;
}
if(counter === 3)
{
sessionTimeClock = "00:" + input + sessionTimeClock.slice(4);
}
if(counter === 1)
{
sessionTimeClock = "0" + input + sessionTimeClock.slice(2);
}
if(counter === 0)
{
sessionTimeClock = input + sessionTimeClock.slice(1);
}
counter--;
if(counter === 2)
{
counter--;
}
}
else if(input === "X")
{
if(counter === 3)
{
sessionTimeClock = "00:0" + sessionTimeClock.slice(4);
}
else if(counter === 1)
{
sessionTimeClock = "00:" + sessionTimeClock.slice(3);
}
else if(counter === 0)
{
sessionTimeClock = "0" + sessionTimeClock.slice(1);
}
}
else if(input === "Enter")
{
return;
}
$(".session-time-clock").text("hello");
});
});
$(".break-time-clock").click(function(){
$(".num-button").css("background-color", "#BCC6CC");
function myFunction() {
myVar = setTimeout(changeBackground, 500);
}
function changeBackground() {
$(".num-button").css("background-color", "#575e62");
}
myFunction();
breakTimeClock = "00:00";
counter = 4;
$("button").click(function(){
// gets button text label
var input = $(this).text();
// if, else if chain for calculator functions
if(input !== "Start" && input !== "Pause" && input !== "Reset" && input !== "X" && input !== "Enter" && counter > -1)
{
if(counter === 4)
{
breakTimeClock = breakTimeClock.slice(0,counter-1) + input;
}
if(counter === 3)
{
breakTimeClock = "00:" + input + breakTimeClock.slice(4);
}
if(counter === 1)
{
breakTimeClock = "0" + input + breakTimeClock.slice(2);
}
if(counter === 0)
{
breakTimeClock = input + breakTimeClock.slice(1);
}
counter--;
if(counter === 2)
{
counter--;
}
}
else if(input === "X")
{
if(counter === 3)
{
breakTimeClock = "00:0" + breakTimeClock.slice(4);
}
else if(counter === 1)
{
breakTimeClock = "00:" + breakTimeClock.slice(3);
}
else if(counter === 0)
{
breakTimeClock = "0" + breakTimeClock.slice(1);
}
}
else if(input === "Enter")
{
return;
}
$(".break-time-clock").text(breakTimeClock);
});
});
The supplied code is not identical to the jsfiddle. I will relate to the jsfiddle:
You have this code:
$("button").click(function(){
if(input === "Start")
{
// start clock code
}
else if(input === "Pause")
{
// pause clock code
}
else if(input === "Reset")
{
sessionTimeClock = "00:00";
breakTimeClock = "00:00";
}
return true;
});
This is the first time you assign a click handler to "button" and therefore it gets called first.
The "input" variable is not defined, and therefore the other handlers are not called. (You can see an error in the Dev Tools console).

How do I prevent both my if statements running the first time?

Quick question as I'm drawing a blank, if I have an event listener that contains 2 if statements that on first time round are both true but I don't want both of them to execute how do I prevent this? Can I break on the first conditional or something like that?
JS
var input = document.querySelector('.js-input'),
output = document.querySelector('.js-output');
input.addEventListener('keydown', function (event) {
if (this.value.length === 0) {
console.log('run this once');
}
if (this.value === '') {
console.log('this is empty so show hint')
}
});
var input = document.querySelector('.js-input'),
output = document.querySelector('.js-output');
var firstTimeCallbackRun= true;
input.addEventListener('keydown', function (event) {
if (this.value.length === 0) {
console.log('run this once');
if(firstTimeCallbackRun) {
firstTimeCallbackRun = false;
return;
}
}
if (this.value === '') {
console.log('this is empty so show hint')
}
});
var input = document.querySelector('.js-input'),
output = document.querySelector('.js-output'),
isFirst = true;
input.addEventListener('keydown', function (event) {
if (isFirst) {
isFirst = false;
return;
}
if (this.value.length === 0) {
console.log('run this once');
}
if (this.value === '') {
console.log('this is empty so show hint')
}
});
Maybe something like that? But probably you should ask yourself why this is happening and what are you doing wrong. Since it is a hacky and not optimal solution.
(function() {
var firstRun = true;
var input = document.querySelector('.js-input');
var output = document.querySelector('.js-output');
input.addEventListener('keydown', function (event) {
if (firstRun) {
firstRun = false;
if (this.value.length === 0) {
console.log('run this once');
}
} else {
if (this.value === '') {
console.log('this is empty so show hint')
}
}
});
})();
Here an example of how you could achieve this:
(function() {
var input = document.querySelector('.js-input');
var isDirty = function(element) {
if ( ! element.data) {
element.data = {isDirty: false};
}
if (element.value.length > 0 && ! element.data.isDirty) {
element.data.isDirty = true;
} else if (element.value.length === 0) {
element.data.isDirty = false;
}
return element.data.isDirty;
};
input.addEventListener('keyup', function (event) {
var dirtyClass = " is-dirty";
if (isDirty(this)) {
if (this.className.search(dirtyClass) === -1) {
this.className += dirtyClass;
}
} else {
this.className = this.className.replace(dirtyClass, "");
}
});
})();

Unintended Recursivity - How do I stop or reset a function on click?

I tried making a jsFiddle for this, but it's not working right (I think because of the alerts I have set up to test my code), so hopefully someone can simply look at my JS and see the problem.
The issue is that when you close the div with the form (#verizoni516) and then re-open it, you get as many alerts as times you have closed the div and re-opened it, instead of the ONE alert I'm intending. Does that make any sense?
Here's the JS:
/*--------------Validation Functions-------------------*/
function chkradio() {
var elem = document.forms['vzi5'].elements['element_0'];
len = elem.length - 1;
chkvalue = '';
sevenPlus = false;
fourToSix = false;
threeMin = false;
for (i = 0; i <= len; i++) {
if(elem[i].checked) chkvalue = elem[i].value;
}
if (chkvalue == '') {
$('#radio-error').fadeIn('fast').effect("bounce", {times:3}, 'fast', function(){
setTimeout(function(){
$('#radio-error').fadeOut('slow');}, 2000);
});
}
if (chkvalue >= 7) {
sevenPlus = true;
} else if (chkvalue >= 4 && chkvalue <= 6) {
fourToSix = true;
} else {
threeMin = true;
}
};
function chkselect() {
var elem = document.forms['vzi5'].elements['element_1'];
len = elem.length - 1;
chkvalue = '';
likeNew = false;
minProb = false;
nonFunc = false;
for (i = 0; i <= len; i++) {
if (elem[i].selected) chkvalue = elem[i].value;
}
if (chkvalue == '') {
elem.focus();
$('#select-error').fadeIn('fast').effect("bounce", {times:3}, 'fast', function(){
setTimeout(function(){
$('#select-error').fadeOut('slow');}, 2000);
});
} else if (chkvalue === 'Like New - No Functional Problems') {
likeNew = true;
} else if (chkvalue === 'Minor Functional Problems') {
minProb = true;
} else {
nonFunc = true;
}
};
function chkbox() {
var elem = document.forms['vzi5'].elements['element_2[]'];
chkvalue = elem.checked;
iUnderstand = true;
if (chkvalue === true) {
iUnderstand;
} else {
iUnderstand = false;
elem.focus();
$('#check-error').fadeIn('fast').effect("bounce", {times:3}, 'fast', function(){
setTimeout(function(){
$('#check-error').fadeOut('slow');}, 2000);
});
}
};
//Calling the validation functions---------------------------
$('#verizon img.apple, #unlocked img.apple').click(function(){
$(this).closest('div').fadeOut(500).animate({"top": "-414px"}, 100).fadeIn('fast', function(){
});
$('#verizon516').animate({"top": "+=557px"}, 500, function(){
$(this).animate({"top": "-=20px"}, 200);
});
$('div.next').click(function(){
chkradio();
chkselect();
chkbox();
if (sevenPlus === true) {
if (likeNew === true && iUnderstand === true) {
alert('Condition is 7+ and functions like new.');
} else if (minProb === true && iUnderstand === true) {
alert('Condition is 7+ and has minor functional problems');
} else if (nonFunc === true && iUnderstand === true) {
alert('Condition is 7+ and device does NOT function.');
} else {
};
};
if (fourToSix === true) {
if (likeNew === true && iUnderstand === true) {
alert('Condition is 4-6 and functions like new.');
} else if (minProb === true && iUnderstand === true) {
alert('Condition is 4-6 and has minor functional problems');
} else if (nonFunc === true && iUnderstand === true) {
alert('Condition is 4-6 and device does NOT function.');
} else {
};
};
if (threeMin === true) {
if (likeNew === true && iUnderstand === true) {
alert('Condition is 1-3 and functions like new.');
} else if (minProb === true && iUnderstand === true) {
alert('Condition is 1-3 and has minor functional problems');
} else if (nonFunc === true && iUnderstand === true) {
alert('Condition is 1-3 and device does NOT function.');
} else {
};
};
});
});
Move the div.next click handler out of the other click handler, it will cause a new handler to get registered every time you click on one of the #verizon img.apple, #unlocked img.apple elements which intern gets called one after another.
/*--------------Validation Functions-------------------*/
function chkradio() {
var elem = document.forms['vzi5'].elements['element_0'];
len = elem.length - 1;
chkvalue = '';
sevenPlus = false;
fourToSix = false;
threeMin = false;
for (i = 0; i <= len; i++) {
if (elem[i].checked) chkvalue = elem[i].value;
}
if (chkvalue == '') {
$('#radio-error').fadeIn('fast').effect("bounce", {
times: 3
}, 'fast', function () {
setTimeout(function () {
$('#radio-error').fadeOut('slow');
}, 2000);
});
}
if (chkvalue >= 7) {
sevenPlus = true;
} else if (chkvalue >= 4 && chkvalue <= 6) {
fourToSix = true;
} else {
threeMin = true;
}
};
function chkselect() {
var elem = document.forms['vzi5'].elements['element_1'];
len = elem.length - 1;
chkvalue = '';
likeNew = false;
minProb = false;
nonFunc = false;
for (i = 0; i <= len; i++) {
if (elem[i].selected) chkvalue = elem[i].value;
}
if (chkvalue == '') {
elem.focus();
$('#select-error').fadeIn('fast').effect("bounce", {
times: 3
}, 'fast', function () {
setTimeout(function () {
$('#select-error').fadeOut('slow');
}, 2000);
});
} else if (chkvalue === 'Like New - No Functional Problems') {
likeNew = true;
} else if (chkvalue === 'Minor Functional Problems') {
minProb = true;
} else {
nonFunc = true;
}
};
function chkbox() {
var elem = document.forms['vzi5'].elements['element_2[]'];
chkvalue = elem.checked;
iUnderstand = true;
if (chkvalue === true) {
iUnderstand;
} else {
iUnderstand = false;
elem.focus();
$('#check-error').fadeIn('fast').effect("bounce", {
times: 3
}, 'fast', function () {
setTimeout(function () {
$('#check-error').fadeOut('slow');
}, 2000);
});
}
};
//Calling the validation functions---------------------------
$('#verizon img.apple, #unlocked img.apple').click(function () {
$(this).closest('div').fadeOut(500).animate({
"top": "-414px"
}, 100).fadeIn('fast', function () {});
$('#verizon516').animate({
"top": "+=557px"
}, 500, function () {
$(this).animate({
"top": "-=20px"
}, 200);
});
});
//move this out of the other click handler
$('div.next').click(function () {
chkradio();
chkselect();
chkbox();
if (sevenPlus === true) {
if (likeNew === true && iUnderstand === true) {
alert('Condition is 7+ and functions like new.');
} else if (minProb === true && iUnderstand === true) {
alert('Condition is 7+ and has minor functional problems');
} else if (nonFunc === true && iUnderstand === true) {
alert('Condition is 7+ and device does NOT function.');
} else {
};
};
if (fourToSix === true) {
if (likeNew === true && iUnderstand === true) {
alert('Condition is 4-6 and functions like new.');
} else if (minProb === true && iUnderstand === true) {
alert('Condition is 4-6 and has minor functional problems');
} else if (nonFunc === true && iUnderstand === true) {
alert('Condition is 4-6 and device does NOT function.');
} else {
};
};
if (threeMin === true) {
if (likeNew === true && iUnderstand === true) {
alert('Condition is 1-3 and functions like new.');
} else if (minProb === true && iUnderstand === true) {
alert('Condition is 1-3 and has minor functional problems');
} else if (nonFunc === true && iUnderstand === true) {
alert('Condition is 1-3 and device does NOT function.');
} else {
};
};
});
Demo: Fiddle
This is because you are binding the click event for div.next inside the click event for #verizon img.apple, #unlocked img.apple, so every time the outer event is clicked, you are re-binding the inner click event. Fix this by moving the event binding for div.next outside the click event for #verizon img.apple, #unlocked img.apple
$('#verizon img.apple, #unlocked img.apple').click(function(){
// .. contents here
});
$('div.next').click(function(){
// ... contents here
});
You are binding the click event to $('div.next') every time $('#verizon img.apple, #unlocked img.apple') is clicked. Which means it will fire once for each time it is bound. Move the code for $('div.next') out of the $('#verizon img.apple, #unlocked img.apple') click handler.

Hide the Tool tip popup after all condition are fulfilled

I have a jquery password live validation form HERE
This example guides to add proper password and show with red and green sign.
But I am wanting something like when all the conditions of password are successful then popup tool tip will automatically disappear.
How can this possible. I am not good at jquery, any help will be much appreciated.
live JS fiddle link
JS
$(document).ready(function() {
$('input[type=password]').keyup(function() {
// set password variable
var pswd = $(this).val();
if ( pswd.length < 8 ) {
$('#length').removeClass('valid').addClass('invalid');
} else {
$('#length').removeClass('invalid').addClass('valid');
}
//validate letter
if ( pswd.match(/[A-z]/) ) {
$('#letter').removeClass('invalid').addClass('valid');
} else {
$('#letter').removeClass('valid').addClass('invalid');
}
//validate capital letter
if ( pswd.match(/[A-Z]/) ) {
$('#capital').removeClass('invalid').addClass('valid');
} else {
$('#capital').removeClass('valid').addClass('invalid');
}
//validate number
if ( pswd.match(/\d/) ) {
$('#number').removeClass('invalid').addClass('valid');
} else {
$('#number').removeClass('valid').addClass('invalid');
}
});
$('input[type=password]').focus(function() {
// focus code here
});
$('input[type=password]').blur(function() {
// blur code here
});
$('input[type=password]').keyup(function() {
// keyup code here
}).focus(function() {
$('#pswd_info').show();
}).blur(function() {
$('#pswd_info').hide();
});
});
One way would be to count the number of valid rules and when you reach the appropriate number, fade the rules out:
if ($('#pswd_info li.valid').length == 4) $('#pswd_info').fadeOut();
jsFiddle example
This will work inside of your keyup() function:
if(pswd.length >= 8 && pswd.match(/[A-z]/) && pswd.match(/\d/)) {
$('#pswd_info').hide();
}
Updated JSFiddle
Here is a working version (jsfiddle):
$(document).ready(function() {
$('input[type=password]').keyup(function() {
var isValid = true;
// set password variable
var pswd = $(this).val();
if ( pswd.length < 8 ) {
isValid &= false;
$('#length').removeClass('valid').addClass('invalid');
} else {
isValid &= true;
$('#length').removeClass('invalid').addClass('valid');
}
//validate letter
if ( pswd.match(/[A-z]/) ) {
isValid &= true;
$('#letter').removeClass('invalid').addClass('valid');
} else {
isValid &= false;
$('#letter').removeClass('valid').addClass('invalid');
}
//validate capital letter
if ( pswd.match(/[A-Z]/) ) {
isValid &= true;
$('#capital').removeClass('invalid').addClass('valid');
} else {
isValid &= false;
$('#capital').removeClass('valid').addClass('invalid');
}
//validate number
if ( pswd.match(/\d/) ) {
isValid &= true;
$('#number').removeClass('invalid').addClass('valid');
} else {
isValid &= false;
$('#number').removeClass('valid').addClass('invalid');
}
if(isValid){
$('#pswd_info').hide();
}
});
$('input[type=password]').focus(function() {
// focus code here
});
$('input[type=password]').blur(function() {
// blur code here
});
$('input[type=password]').keyup(function() {
// keyup code here
}).focus(function() {
$('#pswd_info').show();
}).blur(function() {
$('#pswd_info').hide();
});
});

Categories