Javascript/jQuery, if and else statements both being executed - javascript

I'm not too sure what's going on here and feel I may be missing something that is probably quite obvious, but I have an if else in which both statements are being called. If someone could shed some light on this that would be great. The code below is using asual and should be detecting whether or not a div $('#' + $.address.hash() has already been loaded. However both if and else events are being fired in order. In fact the else statement fires twice...
$('#lmit_back').show(400, function() {
if($('#' + $.address.hash() ).length == 0) {
$('#init').load('inithandler.php', { 'address' : $.address.hash() }, function() {
$('#' + $.address.hash()).fadeIn(1000, function() {
$('#remn').load('pagehandler.php',{ 'address' : $.address.hash() });
});
});
}
else {
alert('hey');
}
});
Here is all the code..I can't really work out what could cause it to execute twice, unless it has something to do with address.change which im not as familiar with as I would like to be.
if (($.address.hash() == '')) {$.address.hash('home');}
$('#lmit_back').click(function() {
$.address.hash('home');
});
$.address.change( function() {
if (!($.address.hash() == 'home'))
{
var exception = '.' + $('[href="#' + $.address.hash() + '"]').parent().attr('class');
$('#left_menu_bar li:not(' + exception + ')').hide(300,function() {
$(exception).show( function() {
$('#left_menu_bar').animate({ width:'100%'},400, function() {
$('#lmit_back').show(400, function() {
if ($('#' + $.address.hash() ).length === 0)
{
$('#init').load('inithandler.php', { 'address' : $.address.hash() } , function() {
$('#' + $.address.hash()).fadeIn(1000, function() {
$('#remn').load('pagehandler.php',{ 'address' : $.address.hash() });
});
});
}
else
{
alert('nigs');
}
});
});
});
});
}
else
{
$('#left_menu_bar').animate({ width:'251px'}, function() {
$('#left_menu_bar li').show( function() {
$('#lmit_back').hide();
});
});
$('#left_menu_bar').css('width','251px');
}
});

The problem here is not arising from the code you have pasted. The only way the code could be running multiple times and hitting multiple branches is if it is being executed more than once. Look to the surrounding code for places where this could be called more than once.

I faced similar issue, while debugging when if condition was true it also went in else block. Later I added alert and console.log in if/else block's & realized, else was not actually being executed but while debugging it looked like it was in else.
So, whoever faces same issue verify by adding alert or console.log.

I was seeing the same behavior, when I debugged step by step it worked. It ended up being that I was attaching multiple click events so the code fired n times.

Related

Is there a simpler way to do the if else statement?

It's been a month since I study the web mapping. I'm currently practicing jQuery` and GeoServer.
Is there a way I to simplify it? Can I use switch here?
bridge.on('change:visible', function(){
if(bridge.getVisible() == true) {
$('#bridge').show();
} else {
$('#bridge').hide();
}
});
road.on('change:visible', function(){
if(road.getVisible() == true) {
$('#road').show();
} else {
$('#road').hide();
}
});
rail.on('change:visible', function(){
if(rail.getVisible() == true) {
$('#rail').show();
} else {
$('#rail').hide();
}
});
The problem isn't really with the if-else-statement that needs simplification, it's the repetition. Wrap the repeated code in a function, factor the differences into parameters, and call it thrice:
function toggleWithVisibility(source, target) {
source.on('change:visible', function(){
if (source.getVisible() == true) {
target.show();
} else {
target.hide();
}
});
}
toggleWithVisibility(bridge, $('#bridge'));
toggleWithVisibility(road, $('#road'));
toggleWithVisibility(rail, $('#rail'));
You also can simplify the functions code by omitting the superfluous == true and by using toggle with an argument:
function toggleWithVisibility(source, target) {
source.on('change:visible', function(){
target.toggle(source.getVisible());
});
}
You didn't yet show us how your three variables are defined, chances are good you might be able to simplify those as well, e.g. selecting source and target together and by calling the function from a loop.
Embrace the functional!
function toggleVisible(thing, selector){
selector.toggle(thing.getVisible());
}
bridge.on('change:visible', toggleVisible.bind(this, bridge, $('#bridge'));
road.on('change:visible', toggleVisible.bind(this, road, $('#road'));
rail.on('change:visible', toggleVisible.bind(this, rail, $('#rail'));
var $list= ["bridge", "road","rail"];
$list.forEach(function(v) {
if($('#'+v').is(":visible")) {
$('#'+v').show();
} else {
$('#'+v').hide();
}
}
});
Hope this help you.
You can use single jQuery() call, .on(), and conditional operator, .filter()
$("#bridge, #road, #rail").on("change:visible", function() {
$(this).toggle(!$(this).getVisible());
});
I have not tested it!
bridge.on('change:visible', function(){
$('#bridge').toggle();
});
road.on('change:visible', function(){
$('#road').toggle();
});
rail.on('change:visible', function(){
$('#rail').toggle();
});

Why won't my balance change?

I'm trying to have a balance go up if the function "neww" is true, and down if false. neww is a random number from 0-1:
Template.result.helpers({
'neww': function(){
return( Session.get('number') > 0.5 ? true : false )
}
});
so this should declare new true or false based on the randomly generated number right? Well, I have an if else statement like this:
Template.balance.events({
'click button': function() {
if (neww = true) {
Session.set('bal', Session.get('bal') + 1);
} else {
Session.set('bal', Session.get('bal') - 1);
}
}
});
It should raise my balance 1 if the number is greater than .5 and lower it otherwise.
My entire code is:
if (Meteor.isClient) {
// counter starts at 0
Session.setDefault('number', Random.fraction());
Session.setDefault('word', "");
Session.setDefault('bal', 5000);
Template.hello.helpers({
number: function () {
return Session.get('number');
}
});
Template.balance.helpers({
bal: function () {
return Session.get('bal');
}
});
Template.hello.helpers({
word: function () {
return Session.get('word');
}
});
Template.hello.events({
'click button': function () {
// increment the counter when button is clicked
Session.set("number", 0+Random.fraction());
}
});
Template.result.helpers({
'neww': function(){
return( Session.get('number') > 0.5 ? true : false )
}
});
Template.balance.events({
'click button': function() {
if (neww = true) {
Session.set('bal', Session.get('bal') + 1);
} else {
Session.set('bal', Session.get('bal') - 1);
}
}
});
}
if (Meteor.isServer) {
Meteor.startup(function () {
// code to run on server at startup
});
}
Any help or tips would be appreciated.
neww, like all helpers, is only available within your templates themselves. If you want to use it in your JS, just make it a normal JS function and call it as normal. You can assign that function to a helper as well if you want to use it in templates too.
At present, neww will be undefined in the context you're trying to use it, so you should see errors in your console when you click the button. The function will throw before it actually does anything, which is why nothing's happening to the balance.
This is not the correct syntax for if
if (neww = true)
neww is not variable, it is a helper, thus you cannot make it in the if like that. In order to let neww is available on the balance template, you need to save it into a global variable like Session
I know that you are new to coding, therefore, learn about basic programming first. Working with frameworks like meteor straight away will make you feel bored gradually
Here's how you can fix the code to make it do what you want:
Template.balance.events({
'click button': function() {
if ( Session.get('number') > 0.5 ) {
Session.set('bal', Session.get('bal') + 1);
} else {
Session.set('bal', Session.get('bal') - 1);
}
}
});
You can completely get rid of your neww helper. To read more about how template helpers, events, and sessions work, checkout the Meteor Guide.

Jquery Animations not waiting for callback

I have a Jquery animation that is running the code from its function before the animation is complete. the Page this code is being used at is no where near complete yet but if you want to take a look it's cottageboards.com/orderform
$('#snow').fadeIn(500, "linear", function () {
$('#largeImage').fadeOut(500, function () {
$('#largeImage').attr('src', selectedimg).load(function () {
$('#largeImage').fadeIn(1000, function () {
//Everything below here is running before the above image's fade in is complete
$('#snow').fadeOut(5000);
var selection = 'input[name="' + $(selectionage).data('type') + '_selection"]';
$($('#selected_thumb').val()).attr('src', $($('#selected_thumb').val()).data('regular'));
$(selectionage).attr('src', $(selectionage).data('selected'));
selectedid = '#' + $(selectionage).attr('id');
$('#selected_thumb').val(selectedid);
$('#selected_info').html($(selectionage).data('desc'));
$('#name').html($(selectionage).data('name'));
if ($(selectionage).data('val') === 99) {
$('#upload').show();
$('#displayinfo').hide();
} else {
$(selection).val($(selectionage).data('val'));
$('#upload').hide();
$('#displayinfo').show();
}
$('#next').prop('disabled', false);
});
});
});
});
When rewritten so the load function comes before the src change it works like a charm. Thanks for the help guys!
Working code:
$('#snow').fadeIn(500, "linear", function () {
$('#largeImage').fadeOut(500, function () {
$('#largeImage').unbind().load(function () {
$('#largeImage').fadeIn(1000, function () {
$('#snow').fadeOut(5000);
var selection = 'input[name="' + $(selectionage).data('type') + '_selection"]';
$($('#selected_thumb').val()).attr('src', $($('#selected_thumb').val()).data('regular'));
$(selectionage).attr('src', $(selectionage).data('selected'));
selectedid = '#' + $(selectionage).attr('id');
$('#selected_thumb').val(selectedid);
$('#selected_info').html($(selectionage).data('desc'));
$('#name').html($(selectionage).data('name'));
if ($(selectionage).data('val') === 99) {
$('#upload').show();
$('#displayinfo').hide();
} else {
$(selection).val($(selectionage).data('val'));
$('#upload').hide();
$('#displayinfo').show();
}
$('#next').prop('disabled', false);
});
}).attr('src', selectedimg);
});
});
You are binding the load function to largeimage every time you click. The first click the load function gets called once, the second time, it gets called twice. I suspect everything is getting messed up because you are firing multiple .fadeIns on the same object, and they are running in parallel.
Only call $('#largeImage').load(...) once, not on every click. Of course, you'll have to do something about your captured vars, but that's a different issue. Alternatively, call $('#largeImage').unbind().load(...)
If that's hard to follow, replace this line:
$('#largeImage').attr('src', selectedimg).load(function () {
with:
$('#largeImage').unbind().attr('src', selectedimg).load(function () {
I tested it by putting a break point after this line:
$('#thumbs').delegate('img','click', function() {
and calling $('#largeImage').unbind(); and everything seemed to work, so you can do it that way too.
see this fiddle for example how to use done : http://jsfiddle.net/gcnes8b2/1/
$('span').click(function() {
$('#1').fadeIn({
duration: 1000,
done:function(){
$('#2').fadeOut(1000);
// etc
}
});
});

jQuery Post Submitting Twice

I have a form that uses a formvalidation.io class. I Have a if statement that says if the field is valid use a jQuery post to submit the data and prepend the data on a table. For Some reason it is submitting twice. If I remove the $.post and prepend the data under the if statement the prepend only does one time. I have the e.preventDefault() at the start of the function. That seams to be the only solution on other forums. Any Help Appreciated:
barcode: {
onSuccess: function(e, data) {
e.preventDefault();
setTimeout(function() {
if (!$('#move_bin').data('formValidation').isValidField('bin')) {
$("#barcode").val("");
$('#move_bin').data('formValidation').updateStatus('barcode', 'NOT_VALIDATED');
$('#move_bin').data('formValidation').updateStatus('bin', 'INVALID');
} else {
setTimeout(function() {
if ($('#move_bin').data('formValidation').isValidField('barcode')) {
$.post( "/?a=scantobin", { bin: $("#bin").val(), barcode: $("#barcode").val() }, function( data ) {
if(data.valid == true){
$("#bin_info tbody").prepend("<tr><td>" + $("#bin").val() + "</td><td>" + $("#barcode").val() + "</td></tr>");
$('#move_bin').data('formValidation').resetField('barcode', true);
$("#barcode").focus();
} else {
alert("Internal Error");
}
}, "json");
}
}, 750);
}
}, 500);
},
There is nothing wrong in your code, may be somewhere in your project you are invoking that function twice.
http://formvalidation.io/examples/form-submit-twice/
This helped me out. I had to place the code in a Form Level instead of the field level on the formvalidation.

how to fix error "Expected identifier, string or number"

I have been fighting this issue for couple of days now and i am not able to resolve this issue because the line where it says the error is is BLANK. my JS code is below:
$(document)
.ready(
function() {
// THE DEBUGGER SAYS THE ERROR IS IN THIS LINE"(script1028
// expected identifier string or number)".
$(document).ajaxStart(function() {
$('#overlay').show();
});
$(document).ajaxStop(function() {
$('#overlay').hide();
});
var html = "";
$('#zipcode,#telephone').autotab_magic().autotab_filter(
'numeric');
$("#backtoTopholder").click(function() {
window.scrollTo(0, 0);
})
preload([ '../img/AjaxLoader.gif' ]);
$("#startover").click(function() {
})
$("#backtoTopholder").hide();
$(function() {
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$('#backtoTopholder').fadeIn();
} else {
$('#backtoTopholder').fadeOut();
}
});
$('#backtoTopholder a').click(function() {
$('body,html').animate({
scrollTop : 0
}, 800);
return false;
});
});
$(".addressMatch").click(function() {
alert("index");
});
preload([ '../img/step1.png', '../img/step2.png',
'../img/step3.png', '../img/step4.png',
'../img/step5.png', '../img/step6.png',
'../img/add_to_cart_button_off.png',
'../img/add_to_cart_button_on.png' ]);
$.ajaxSetup({
cache : false,
global : true
});
$("#existingCustomer").change(function() {
switch (this.value) {
case "No":
$("#WTNRow").hide();
break;
case "Yes":
$("#WTNRow").show();
break;
default:
break;
}
})
$("#plus4")
.click(
function() {
if (!$("#address").val()
|| !$("#city").val()
|| !$("#state").val()) {
alert("In order to do verify the zip code you need to fill out the address,city and state");
return false;
}
var data = $("#searchPackages")
.serialize();
var requestZipCode = $
.ajax({
url : "classes/Dispatcher.php?Ziplookup=1",
type : "POST",
dataType : "text",
cache : 'false',
data : data
});
requestZipCode
.success(function(data) {
var result = data;
if ($.trim(result) == "not found") {
$("#zipCodeReturnmsg")
.html("");
$("#zipCodeReturnmsg")
.html(
"<font color=\"red\">could retrieve a valid zipcode, please review your address and try again.Please select a unit Suffix.</font>");
} else {
$("#zipCodeReturnmsg")
.html("");
$("#zipcode")
.val(
$(
"#zipcode")
.val()
+ $
.trim(result));
$("#zipCodeReturnmsg")
.html(
"<font color=\"green\">zip code retrieved successfully.</font>");
}
});
requestZipCode
.fail(function(jqXHR, error,
errorThrown) {
$("#test").html(
jqXHR.responseText);
});
})
});
I overlooked for extra commas and reserved words and i believe i didn't miss any. Any help to fix this will be very thankful.
I am suing jquery version 1.10.2.
thank you very much
The indentation makes it very hard to read what's going, I believe you're missing a few semicolons. For example:
$("#backtoTopholder").click(function(){
window.scrollTo(0,0);
})
preload(['../img/AjaxLoader.gif']);
should this be:
$("#backtoTopholder").click(function(){
window.scrollTo(0,0);
});
preload(['../img/AjaxLoader.gif']);
?
There is nothing wrong with what you posted here. Your error is elsewhere. Fiddly proof here.
// some code because Stack Overflow complains to JSFiddle links
// without accompanying code...
// even though I just posted the exact same code that OP did
// only with filler functions to stub for code he did not post
// >.<

Categories