Global Var value not assigning inside function - javascript

When i mouseenter through the #infobox div the value is not assigned to true . the value is assigned as false always ! But the console.log("in") segment is executed. Is there s anything wrong with my code
var infoChk = false;
$("#infobox").mouseenter(function(){
console.log("in")
infoChk = true;
});
if(infoChk == false){
console.log("false")
}
else{
console.log("true")
}

Your code is correct but you are checking the value of the variable the wrong way.
To show you that your variable is being set correctly you can do like the code below.
var infoChk = false;
$("#infobox").mouseenter(function(){
console.log("in");
infoChk = true;
showVariableValue();
});
function showVariableValue() {
console.log(infoChk);
}
You can see it in action here in jsFiddle

I think you misinterpreted your own code.
The first code block is runned as an event. Every time your mouse enters div#infobox it will be runned. However, the if statement is runned once, returning false. This is because the code is runned immediately and your mouse is most likely OUT of the box.
Try:
var infoChk = false;
$("#infobox").mouseenter(function()
{
infoChk = true;
console.log('Entered!');
}).mouseleave(function()
{
infoChk = false;
console.log('Leaved!');
});

Related

How to check if any one value not equals and stop calling function within each function using jquery?

in the given code, if any of the input value not equal to the attribute value,it returns false and dont call the function "printDiv()".This printDiv function for window.print().Now if each function fails also calling printdiv after print page opens in another windows then only error alert message showing.If any one the value fails within each function only want to show alert message and dont call printdiv function
How to fix this issue?
$("#btnprint").click(function(e) {
var isValid = true;
$('#printcontent').hide();
var orginaladv = $('#orginal_advamt').val();
var orginalbal = $('#orginal_balamt').val();
var changeadv = $('#advamt').val();
var changebal = $('#balamt').val();
$('.checkattrval').each(function() {
e.preventDefault();
if($(this).val() != $(this).attr('data-orgval')) {
alert("You should update first");
isValid = false;
return false;
}
else {
printDiv();
}
});
return isValid;
});
Move the call to printDiv() outside the loop, and have it check isValid there. Otherwise you call it for each valid field until you get to an invalid one.
$("#btnprint").click(function(e) {
var isValid = true;
$('#printcontent').hide();
var orginaladv = $('#orginal_advamt').val();
var orginalbal = $('#orginal_balamt').val();
var changeadv = $('#advamt').val();
var changebal = $('#balamt').val();
$('.checkattrval').each(function() {
e.preventDefault();
if ($(this).val() != $(this).attr('data-orgval')) {
alert("You should update first");
isValid = false;
return false;
}
});
if (isValid) {
printDiv();
}
});

Changing boolean value on document click

sorry for this very basic question but it's makes me crazy, I don't understand what is not working on this very simple Jquery code.
I just want to change my "abc" boolean from false to true when clicking on my document and launch an alert when "abc" is true (just for exemple).
$(document).ready(function(){
var abc = false;
$(document).click(function(){
abc = true;
});
if (abc == true){
alert("ALERT");
//do some other things
}
});
Somebody to help ? Thanks
This is caused by JavaScript using an event model. This is your piece of code with detailed explanations:
var abc = false;
$(document).click(function() {
// Note that this function is attached to the `click` event
// It will be triggered only when the `click` event is triggered
// This means that the code inside it is not executed at the moment
abc = true;
});
// abc is false at the moment so the if statement won't execute
if (abc == true) {
alert("ALERT");
//do some other things
}
To fix this, just put the if statement inside the click handler and it will work fine.
$(document).ready(function() {
var abc = false;
$(document).click(function(){
abc = true;
if (abc == true){
alert("ALERT");
//do some other things
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your alert won't launch because it is not inside the click handler. It executes only once when document loaded and stays calm. You should move your checking inside click
$(document).click(function(){
abc = true;
if (abc == true){
alert("ALERT");
//do some other things
}
});
moreover, for boolean values you can directly write the varaible name inside if condition as if expect a boolean anyway
if (abc == true){
can be shorten to
if (abc){
So, after putting all your pieces together,
$(document).ready(function() {
var abc = false;
$(document).click(function() {
abc = true;
if (abc) {
alert("ALERT");
//do some other things
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

javascript which I wrote is wrong(may be)

I have tried to write js for my html form. js is working fine with the logically. But if logic fails,I mean if any condition fails it reloads the page,which I don't want. I am providing the code. Please point me out the mistake in js if any.
window.onload = function() {
document.getElementById('submitlink').onclick = function() {
var bflag = document.addpro.brandflag;
var brand = document.addpro.brand1.value;
var cflag = document.addpro.catflag;
var cat = document.addpro.cat1.value;
var color1 = document.addpro.color1.value;
var color2 = document.addpro.color2.value;
if(cb_validation(bflag,brand))
{
if(cb_validation(cflag,cat))
{
if(colorcheck(color1,color2))
{
document.getElementById('addproform1').submit();
return false;
}
}
}
}
function cb_validation(flag,field)
{
if(flag[0].checked)
{
if(field==0)
{
alert('Please Select Both Brand And Category');
field.focus();
return false;
}
else
return true;
}
else
return true;
}
function colorcheck(c1,c2)
{
if((c1==0) && (c2==0))
{
alert('Please Select Both Colours');
document.addpro.color1.focus();
return false;
}
else if((c1==0))
{
alert('Please Select 1st Colour');
document.addpro.color1.focus();
return false;
}
else if((c2==0))
{
alert('Please Select 2nd Colour');
document.addpro.color2.focus();
return false;
}
else
return true;
}
}
I am rookie in js. Please also tell me if I have done any mistake.
return false is what keeps the page from reloading. Right now it is inside your final color check condition. If you never want the page to reload it needs to be after your first cb_validation condition.
Submit() is causing the page refresh which is in below line
document.getElementById('addproform1').submit();
Also both your function is returning true becauseyou are returning true in else block. Hope this points you to right direction....
Good luck....

e.preventDefault doesn't work 2

Can anyone help me to find out why this script doesn't work? After hitting the submit button, my form is still being submitted.
Here is the code:
submitadd.submit(function(e){
var submitadd = jQuery('#submitadd'),
yearofmanufacturing = jQuery('#yearofmanufacturing'),
price = jQuery('#price'),
addtext = jQuery('#addtext');
if(yearofmanufacturing.val()==''){
jQuery('#yearofmanufacturing').addClass('bordered2');
jQuery('#yearofmanufacturing').removeClass('styled_select');
jQuery("#yearofmanufacturing").attr("placeholder", "Εισάγετε Χρονολία").placeholder();
e.preventDefault();
return false;
alert('yearof......enter in the if');
}
else {
alert("yearnotempty?");
}
if(price.val()=='') {
jQuery('#price').addClass('bordered2');
jQuery('#price').removeClass('styled_select');
jQuery("#price").attr("placeholder", "Εισάγετε τιμή").placeholder();
e.preventDefault();
return false;
alert('price...enter in the if');
}
if(addtext.val()==''){
jQuery('#addtext').addClass('bordered2');
jQuery('#addtext').removeClass('styled_select');
jQuery("#addtext").attr("placeholder", "Εισάγετε περιγραφή αγγελίας").placeholder();
e.preventDefault();
return false;
alert('add text...enter in the if');
}
alert('addtext = ' +addtext.val());
});
None of the alerts shows when the submit has been clicked. Any help will be deeply appreciated.
Regard, John
To save space you could do something like this:
JQuery
jQuery('#submitadd').submit(function(){
var checks = [jQuery('#yearofmanufacturing'),
jQuery('#price'),
jQuery('#addtext')];
for(var i = 0; i < checks.length; i++){
var x = checks[i];
if(x.val() == ''){
x.addClass('bordered2').removeClass('styled_select');
x.prop("placeholder", "Εισάγετε Χρονολογία");
console.log('Value for ' + x.prop('id') + ' is empty.');
return false;
}
else {
console.log('Value for ' + x.prop('id') + ' is not empty.');
}
}
});
Demo
I have rewritten most of the function but it still does the same stuff. I have removed e.preventDefault();, instead I am using return false;.
If the value is empty. This is also logged to the console (console.log()), this is visible when you debug with F12
Note Aksu's answer too:
You have specified the submitadd variable inside the event. You must move it outside to get event handler fire, otherwise the variable isn't defined, and the code doesn't work.
You have specified the submitadd variable inside the event. You must move it outside to get event handler fire, otherwise the variable isn't defined, and the code doesn't work.
var submitadd = jQuery('#submitadd');
// user fill all fields as it should, so form can be submitted
submitadd.submit(function(e){
var yearofmanufacturing = jQuery('#yearofmanufacturing'),
price = jQuery('#price'),
addtext = jQuery('#addtext');
...
change this:
submitadd.submit(function(e){
to this:
jQuery('#submitadd').submit(function(e){
In your case the variable submitadd is been used before its been declared.
or you can declare it before submit:
var submitadd = jQuery('#submitadd')
submitadd.submit(function(e){
The solution: Move var submitadd = jQuery('#submitadd'); out of your function!
I would recommend you some things:
Use your jQuery variables:
Instead of using yearofmanufacturing, you write jQuery('#yearofmanufacturing') multiple times
Naming conventions:
I would recommend you to use variable names like $price instead of price, if you are declaring jQuery objects.
Don't write unreachable code:
You are trying to call alert() after returning something. This doesn't makes any sense.
Don't abuse alert() for debug issues:
Use console.log(), console.debug(), console.info() and console.warn() for best debugging exceperience.
Crossbrowser support:
Internet Explorer <= 8 doesn't know .preventDefault(). Be happy with something like this:
(e.preventDefault) ? e.preventDefault() : e.returnValue = false;

jQuery if (x == y) not working

So, I have some faux checkboxes (so I could style them) that work with jQuery to act as checked or not checked. There are a number of faux checkboxes in my document, and for each one I have a click function:
var productInterest = [];
productInterest[0] = false;
productInterest[1] = false;
productInterest[2] = false;
// here is one function of the three:
$('#productOne').click(function() {
if (productInterest[0] == false) {
$(this).addClass("checkboxChecked");
productInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
productInterest[0] = false;
}
});
The problem seems to be that there is an error in the if statement, because it will check, but not uncheck. In other words it will add the class, but the variable won't change so it still thinks its checked. Anybody have any ideas? Thanks for your help.
UPDATE: So, I need to show you all my code because it works in the way I supplied it (thanks commenters for helping me realize that)... just not in the way its actually being used on my site. so below please find the code in its entirety.
Everything needs to happen in one function, because the UI and data for each checkbox need to be updated at once. So here is the complete function:
$('input[name=silkInterest]').click(function() { // they all have the same name
var silkInterest = [];
silkInterest[0] = false;
silkInterest[1] = false;
silkInterest[2] = false;
if ($(this).is('#silkSilk')) { // function stops working because the .is()
if (silkInterest[0] == false) {
$(this).addClass("checkboxChecked");
silkInterest[0] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[0] = false;
}
alert(silkInterest[0]);
}
if ($(this).is('#silkAlmond')) {
if (silkInterest[1] == false) {
$(this).addClass("checkboxChecked");
silkInterest[1] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[1] = false;
}
}
if ($(this).is('#silkCoconut')) {
if (silkInterest[2] == false) {
$(this).addClass("checkboxChecked");
silkInterest[2] = true;
} else {
$(this).removeClass("checkboxChecked");
silkInterest[2] = false;
}
}
var silkInterestString = silkInterest.toString();
$('input[name=silkInterestAnswer]').val(silkInterestString);
// This last bit puts the code into a hidden field so I can capture it with php.
});
I can't spot the problem in your code, but you can simply use the class you're adding in place of the productInterest array. This lets you condense the code down to a single:
// Condense productOne, productTwo, etc...
$('[id^="product"]').click(function() {
// Condense addClass, removeClass
$(this).toggleClass('checkboxChecked');
});
And to check if one of them is checked:
if ($('#productOne').hasClass('checkboxChecked')) {...}
This'll make sure the UI is always synced to the "data", so if there's other code that's interfering you'll be able to spot it.
Okay, just had a palm to forehead moment. In regards to my revised code- the variables get reset everytime I click. That was the problem. Duh.

Categories

Resources