Javascript function if statement not excuted right - javascript

I have this little piece of code that is supposed to do something if some if conditions are met. It does not work as it should and I could not figure out why. The code is a bit lengthy please bear with me.Any kind of help is really appreciated!
First I have a button in my html, when it is click it will trigger function
function coverCard() {
if (2 > 1) {
GodAn();
} else {
if (bbbbb === 0) {
do something
} else {
do sth
}
}
}
This function will lead to GodAn function shown as follow
function GodAn() {
var a = 1
if (a < 2) {
document.getElementById("coverCard").onclick = Alert.render("do option 1 please")
bbbbb = 0;
} else {
document.getElementById("coverCard").onclick = Alert.render("do option 2 please")
bbbbb = 2;
}
}
Finally following is the function defining what is shown in the dialog box and what will happen when its ok button is clicked
function CustomAlert() {
this.render = function (dialog) {
document.getElementById('dialogboxfoot').innerHTML = '<button onclick="Alert.ok()">ok</button>';
}
if (bbbbb === 0) {
this.ok = function () {
alert("do option1")
console.log(bbbbb)
}
}
else this.ok = function () {
alert("do option 2")
console.log(bbbbb)
}
}
var Alert = new CustomAlert();
What I expect to happen is when the html button is clicked, the dialog box will show "do option 1 please", (which it always does) and then alert "do option1". However sometimes in the CustomAlert function the "do option 2" alert will be wrongly triggered, even when the global var bbbbb is reset to 0. (console.log also confirms bbbbb is 0).
I have uploaded the original html file and the link is here:
https://wetransfer.com/downloads/313ba63c7a101f917cbc9e6f9a4c5ade20170226122032/43cedb
This really drives me crazy so somebody please shed some light here please?
Here is the jsFiddle link to my code
https://jsfiddle.net/5bn0ux5k/
It seems to me that whether alert 1 or alert 2 is triggered is a pure random event while it is expectedly set to just alert 1(option 1)

A few issues:
You assign a new value to the button onclick handler, ... when you click it. This seems wrong, and all the more so because you do not assign it a function:
document.getElementById("coverCard").onclick = Alert.render("do option 1 please")
What happens here is that the render method is executed immediately. This is all very confusing, because it looks like you wanted to do this:
document.getElementById("coverCard").onclick = function () {
Alert.render("do option 1 please");
};
... which would make the render method execute on the next click, but then in your description you say you actually do want the render method to execute upon the first click, not on the next. So in that latter case, you should just execute the render method, and not assign anything to the onclick method:
Alert.render("do option 1 please");
Doing the mix of both is wrong: the render method does not return a function, so its result should not be assigned to an onclick property. So I'll assume you want just to execute render.
The second issue is that you decide the assignment for this.ok at the moment the page loads, i.e. when new CustomAlert() is executed:
if (bbbbb === 0) {
this.ok = function() {
alert("do option1")
console.log(bbbbb)
}
} else
this.ok = function() {
alert("do option 2")
console.log(bbbbb)
}
Your decision is based on the value of b, which at that moment is random. Later, when you click the button, you change the value of b to zero, but that does not influence that earlier decision any more: this.ok will not magically change because of setting b to zero.
You can correct this, by putting the condition on b inside the this.ok function, like this:
this.ok = function() {
if (bbbbb === 0) {
alert("do option1")
} else {
alert("do option 2")
}
console.log(bbbbb)
}
Now you will have the correct option mentioned in the alert.

Related

Hot to re-active preventDefault function in javascript

When user clicked on submit button, I need to check some validations before submition. If entered data is not valid page should not be submit.
$(document).ready(function() {
$("#colomnChange").submit(function(e) {
var testA = 1;
if (testA == 1) {
testA = 2;
//e.preventDefault();
return false;
} else {
return true;
}
});
});
I can stop the submition using priventDefault function in js. But again user clicked on submit button after correct the wrong data, page should be submit well. How can I re-active the default function.
The answer is: you always go into the first if (because you set the variable to 1 then check if it equals 1, which is always true)
Change testA = 1 to testA = 2 and your event will go into the else which does not have the preventDefault() method so your event will carry on

Close a bootstrap warning when clicking anywhere on page

Bootstrap Warnings Image I have two different types of bootstraps alerts (warning and danger). Danger alerts are always suppose to be on the page no matter what. Warning alerts happen when user clicks on the dropdown list carriers it displays a bootstrap warning notification. User has to click on 'x' for it to close. I need it to work when user click anywhere on the page or by clicking on the 'x'.
HomeController.cs
case "Carrier":
var carrierid = (from foo in db.Carriers
where foo.ID == warningid
select foo.WarningID).Single();
if (carrierid != null)
{
warning = (from warnings in db.Warnings
where warnings.IsActive == true && warnings.Id == carrierid
select warnings.WarningBody).SingleOrDefault();
if (warning != null)
{
warning = ("<div class=\"alert alert-warning alert-dismissible\" id=\"myWarning\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">×</span></button><strong>" +
warning + "</strong></div>");
}
else
{
warning = "";
}
}
else
{
warning = "";
}
return Json(warning, JsonRequestBehavior.AllowGet);
default:
break;
warningwriter.js
//// warning display script takes a value of warningid and warningcaller
$(document).ready(function () {
var warningid = 0;
var warningcaller = "Universal";
loadWarnings(warningid, warningcaller);
});
$('#Phones').change(function () {
var warningid = $(this).val();
var warningcaller = "Phone";
loadWarnings(warningid, warningcaller);})
$('#Carriers').change(function () {
var warningid = $(this).val();
var warningcaller = "Carrier";
loadWarnings(warningid, warningcaller);})
function loadWarnings(warningid, warningcaller) {
$.getJSON("../Home/LoadWarnings", { warningID: warningid, warningCaller: warningcaller },
function (warning) {
var select = $('#warnings');
select.append(warning);
});
};
As Martin suggested, it's something you need to do in javascript. I haven't tested this, but it would be something like:
$(document).click(function (event) {
$(".alert").hide();
});
This is basically, clicking anywhere on the page will hide any displayed alert.
Since you have two different types of bootstraps alerts (danger and warning). You have to use ".alert-warning" because that is the one you want to get rid of when user did a mouse click anywhere on page. ".alert" is all of the bootstraps alerts, however, if you need to get rid of a certain type you can call the contextual classes(e.g., .alert-success, .alert-info, .alert-warning, and/or .alert-danger. https://v4-alpha.getbootstrap.com/components/alerts/
$(document).click(function (event) {
$(".alert-warning").hide();
});
$(document).ready(function () {
$("#myWarning").click(function () {
$(".alert").alert("close");
});
});
By doing this, u are making two things wrong:
You are binding the click event to an element, that possibly
doesnt exist when the page is loaded.
You are binding the click
event to a restricted element. This means that the alert wont be
closed when u click anywhere on the page. In this case, only clicks on #myWarning will close the alert.
Finally, you should use what #Bryan already posted :)
Edit:
Assuming that u have a set of alerts that u always want to close on page load, add to this elements a way to identify them, for example a class "close-on-screenclick"
$(document).click(function () {
$(".close-on-screenclick.alert").alert("close");
});
.This should close those elements whenever a click is made on the screen

Change variable value on button click

very new to JS, I'm struggling with my current project: Trying to insert some HTML via a function if a variable = "yes". The variable value will change on a button click.
I've been using firebug to look at the variable value - it doesn't seem to be changing on the button click.
Was hoping someone would be kind enough to help.
I THINK my main issue is with setting the variable value - but I could of course be wrong so I've attached a codepen version for good luck :)
HTML:
<button id="butterbutton" onclick="imageAdd('yes'); ">
<img id="worldimg" src="http://butterybeast.hol.es/world.png"></img>
</button>
JS:
var beast
function imageAdd(choice) {
beast = choice;
}
if (beast = "yes" ) {
function imagemap () {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
}
http://codepen.io/Puffincat/pen/Nrdgrz?editors=1010
You have just a couple of problems with your code. The first is this:
if (beast = "yes") {
In this case, you're assigning "yes" to beast, not comparing it. Change it to
if (beast == "yes") {
Next, your code at the bottom (if (beast == "yes") { ...) is only run at the start. Instead, you want that code to run whenever the variable is updated. Move it into your imageAdd function or somewhere else where you update the UI then call it from imageAdd. While you're at it, remove that imagemap function declaration. It doesn't make sense to declare a function inside of an if statement.
var beast;
function imageAdd(choice) {
beast = choice;
updateUI();
}
function updateUI() {
if (beast == "yes") {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
}
You have a function imagemap wrapped in a conditional but you aren't calling that function.
Also for your conditional, beast will always be null since the conditional is called straight away.
Consider the following adjustment
var beast;
function imagemap () {
document.getElementById('test1').innerHTML += '<img> an image map goes here';
}
function imageAdd(choice) {
beast = choice;
if (beast === "yes" ) {
imagemap();
}
}

Pure JS "If stament depending the number of click"

I was searching for this problem but I didn't find a solution. I'm trying to create a code where when you click a button do one thing, and when you press the same button later do other thing. I tried to create and "if-else" statement but I can't (don't know) how to count the number of clicks.
The code is:
<button type="submit" id="btnshwmap" onClick="init()" >Show Map</button>
And the if-else :
function init() {
var click =0;
if (click === 0) {
do this
var click = 1;
} else {
do this
}
});//end click
Basically I'm trying to use this example Jquery if its the first time element is being clicked
But the answer are using Jquery I'm trying not use any library.
Thanks a lot!
The problem is that you keep on resetting click=0 every time you call the function.
I would suggest something like this:
function init() {
if( !init.click) {
// first, third, fifth etc.
init.click = 1;
]
else {
// second, fourth...
init.click = 0;
}
}
You just need to have the click counter outside the function, in the global area.
var click =0;
function init() {
if (click == 0) {
//do this once
click = 1;
} else {
//do this every other time
}
});//end click
You could try toggling the value set for the button with the click. Something like:
function init() {
var value = document.getElementById('btnshwmap').value;
if (value === 1) {
do this
document.getElementById('btnshwmap').value = 2;
} else {
do this
document.getElementById('btnshwmap').value = 1;
}
});//end click
Or keep a global variable to track the click status, rather than setting it every time you run the function.

Function called at the start of page loading - javascript

I have a problem; for some reason, my function is being called at the start of the webapplication while the page is loading.
My code is as follows
function validateName(element) {
var len = element.value.length;
//checks if the code is than 6 characters
if (len == 0) {
element.style.backgroundColor="red";
if (element.id == "firstname")
{
document.getElementById('firstNameError').style.display = "block";
}
else if (element.id == "lastname") {
document.getElementById('lastNameError').style.display = "block";
}
return true;
} //if == 0
else {
element.style.backgroundColor="green";
if (element.id == "firstname")
{
document.getElementById('firstNameError').style.display = "none";
}
else if (element.id == "lastname") {
document.getElementById('lastNameError').style.display = "none";
}
return false;
} // if != 0
}
The logic of this function is to validate the text boxes where the user enters their name. Basically,the problem i am facing is as soon as I open up my web page, the text boxes are red, and say 'Your first name cannot be blank!' (which is the firstNameError). Then, once I enter the text in my text box, it doesn't change, it still stays red, and displays the error.
This is how i am calling the function:
function init() {
var firstName = initToolTip("firstname", "firstnameTip");
var lastName = initToolTip("lastname", "lastnameTip");
var promoCode = initToolTip("promocode", "promocodeTip");
//opens the TOS window when you click 'terms and conditions' link
document.getElementById("clickedTOS").onclick = function() { sAlert(document.getElementById("TOS").innerHTML) };
//checks the length of the promo code
promoCode.onblur = validatePromoCode(promoCode);
//checks the validity of a name (is not blank)
firstName.onblur = validateName(firstName);
lastName.onblur = validateName(lastName);
//document.getElementById('submitButton').onmousedown = validateForm();
}
I don't understand why it's being called as soon as the page loads, since it's set, to be called onblur.
can anyone suggest ways to fix this?
You need to pass function references to onblur, not the result of immediately calling a function. Change to this:
function init() {
var firstName = initToolTip("firstname", "firstnameTip");
var lastName = initToolTip("lastname", "lastnameTip");
var promoCode = initToolTip("promocode", "promocodeTip");
//opens the TOS window when you click 'terms and conditions' link
document.getElementById("clickedTOS").onclick = function() { sAlert(document.getElementById("TOS").innerHTML) };
//checks the length of the promo code
promoCode.onblur = function() {validatePromoCode(promoCode);};
//checks the validity of a name (is not blank)
firstName.onblur = function() {validateName(firstName);};
lastName.onblur = function() {validateName(lastName);{;
//document.getElementById('submitButton').onmousedown = validateForm();
}
This changes each onblur assignment to take an anonymous function reference that will be executed later when the onblur event happens, not immediately like your current code was doing.
You're not passing the function to onblur in init; you are passing the result of the function.
See the following example:
var Afuntion=function(){
console.log("hello from function");
return 22;
}
Element.onblur=Afunction("something");//Element.onblur is now 22 and
// "hello from function" is logged
Element.onblur=Afunction; //now onblur has a reference to the function
Element.onblur();//this will log "hello from function" and return 22
Youre not using a library like jQuery to make attaching/adding event listeners easy so it's a bit of a pain to set the event listener using pure JS and read the event in the function. There must be some info on SO how to do this already anyway
In your case you could try this:
promoCode.onblur = function(){ validatePromoCode.call(promoCode,promCode);};

Categories

Resources