Else condition is not working in javascript - javascript

I'm a beginner to JavaScript. Can someone help me in this regard?
In the below code the logic for submit button doesn't work. _btn.addEventListener. Only the if part is getting executed, some issue with the else part condition. If the "if" condition gets satisfied then the alert is getting executed and not the conditions in else part even if the date and image is clicked.
<p align=center>
<input type="submit" value="submit" id="button">
</p>
<script type="text/javascript">
let _img = document.getElementById("img");
let _img1 = document.getElementById("img1");
let _img2 = document.getElementById("img2");
let _picker = document.getElementById("picker");
let _btn = document.getElementById("button");
let isImgClicked = false;
let isDatePicked = false;
/*let ImgClicked = '_img';
let ImgClicked1 = '_img1';
let ImgClicked2 = '_img2';
let DatePicked = '2019';
let DatePicked1 = '2020';*/
_img.addEventListener("click", function(){
isImgClicked = true;
ImgClicked=true
});
/*_img1.addEventListener("click", function(){
ImgClicked1 = true;
});
_img2.addEventListener("click", function(){
ImgClicked2 = true;
}); */
_picker.addEventListener("click", function(){
isDatePicked = true;
});
_btn.addEventListener("click", function(){
if(!isImgClicked || !isDatePicked)
{
alert("select the Year and Click the car image");
}
else
{
if((isImgClicked == "_img") && (isDatePicked == "DatePicked"))
{
window.location.replace("sample1.html");
}
else if((isImgClicked == "_img") && (isDatePicked == "DatePicked1"))
{
window.location.replace("sample2.html");
}
else
{
if((isImgClicked == "_img1") && (isDatePicked == "DatePicked"))
{
window.location.replace("sample3.html");
}
else if((isImgClicked == "_img1") && (isDatePicked == "DatePicked1"))
{
window.location.replace("sample4.html");
}
else
{
alert("!!!!");
}
}
}
});
</script>

Here you are assigning isImgClicked = true and ImgClicked = true
img.addEventListener("click", function(){
isImgClicked = true;
ImgClicked=true
});
But you are comparing this boolean with strings. Why?
if((isImgClicked == "_img1") && (isDatePicked == "DatePicked1"))
Fix it.

This is your function re-written in early-return style:
function() {
if(!isImgClicked || !isDatePicked) {
alert("select the Year and Click the car image");
return
}
if((isImgClicked == "_img") && (isDatePicked == "DatePicked")) {
window.location.replace("sample1.html");
return
}
if((isImgClicked == "_img") && (isDatePicked == "DatePicked1")) {
window.location.replace("sample2.html");
return
}
if((isImgClicked == "_img1") && (isDatePicked == "DatePicked")) {
window.location.replace("sample3.html");
return
}
if((isImgClicked == "_img1") && (isDatePicked == "DatePicked1")) {
window.location.replace("sample4.html");
return
}
alert("!!!!");
}
Which if statement are you having a problem with?

Related

Delete a button upon click

I'm trying to get my button to delete itself after being clicked, as it shouldn't be clicked twice, and I think I may get the reference error because I'm using an online compiler. I also have a hard time changing to jquery, as it seems to mess up everything else I wrote.
I've looked through a ton of stack overflow pages, none of them seem to have malfunctioning code after the switch to jquery. I would prefer to have a way to do this in base html, but if not, I hope someone can explain how to make the switch.
var clicks = 0;
var cursor1 = false;
var autoclicker = false;
//Click Button And Cursor Upgrade
document.getElementById("clickMe").onclick = function() {
clicks++;
if (cursor1 == true) clicks++;
document.getElementById('output').innerHTML = clicks;
document.getElementById("Cursors").onclick = function() {
//PAY UP, PEASANT
clicks -= 100;
//NO MONEY, NO SERVICE
if (clicks < 0) {
clicks += 100;
alert("You are too poor! Peasant...");
} else if (cursor1 == true) {
clicks += 100;
alert("You can't do that!")
} else {
cursor1 = true;
alert("You bought an extra cursor!");
}
document.getElementById('output').innerHTML = clicks;
}
}
//Autoclicker
var delay = 1000;
var autoClick1 = false;
var autoClick2 = false;
var autoClick3 = false;
var autoClick4 = false;
var autoClick5 = false;
var autoClick6 = false;
var autoClick7 = false;
var autoClick8 = false;
var autoClick9 = false;
var autoClick0 = false;
document.getElementById("AutoClicker").onclick = function() {
clicks -= 250;
if (clicks < 0) {
clicks += 250;
alert("You are too poor! Peasant...");
} else if (autoclicker == true) {
clicks += 250;
alert("You can't do that!");
} else {
autoclicker = true;
alert("You bought the autoclicker!");
document.getElementById('output').innerHTML = clicks;
setInterval(clickIncrement, delay);
$("input").remove("AutoClicker");
}
}
var autoCMax = false;
document.getElementById("moreAutoC").onclick = function() {
clicks -= 250;
if (clicks < 0) {
clicks += 250;
alert("You are too poor! Peasant...");
} else if (autoCMax == true) {
clicks += 250;
alert("It's already maxed!");
} else {
if (autoClick0 == false) {
autoClick0 = true;
alert("You bought 1 more autoclicker! Autoclickers:2");
} else if (autoClick0 == true && autoClick1 != true) {
autoClick1 = true;
alert("You bought 1 more autoclicker! Autoclickers:3");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 != true) {
autoClick2 = true;
alert("You bought 1 more autoclicker! Autoclickers:4");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 == true && autoClick3 != true) {
autoClick3 = true;
alert("You bought 1 more autoclicker! Autoclickers:5");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 == true && autoClick3 == true && autoClick4 != true) {
autoClick4 = true;
alert("You bought 1 more autoclicker! Autoclickers:6");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 == true && autoClick3 == true && autoClick4 == true && autoClick5 != true) {
autoClick5 = true;
alert("You bought 1 more autoclicker! Autoclickers:7");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 == true && autoClick3 == true && autoClick4 == true && autoClick5 == true && autoClick6 != true) {
autoClick6 = true;
alert("You bought 1 more autoclicker! Autoclickers:8");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 == true && autoClick3 == true && autoClick4 == true && autoClick5 == true && autoClick6 == true && autoClick7 != true) {
autoClick7 = true;
alert("You bought 1 more autoclicker! Autoclickers:9");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 == true && autoClick3 == true && autoClick4 == true && autoClick5 == true && autoClick6 == true && autoClick7 == true && autoClick8 != true) {
autoClick8 = true;
alert("You bought 1 more autoclicker! Autoclickers:10");
} else if (autoClick0 == true && autoClick1 == true && autoClick2 == true && autoClick3 == true && autoClick4 == true && autoClick5 == true && autoClick6 == true && autoClick7 == true && autoClick8 == true && autoClick9 != true) {
autoClick9 = true;
alert("You bought 1 more autoclicker! Autoclickers:11");
autoCMax = true;
} else {
alert("It's already maxed!")
}
if (autoClick0 == true)
setInterval(clickIncrement, delay);
if (autoClick1 == true)
setInterval(clickIncrement, delay);
if (autoClick2 == true)
setInterval(clickIncrement, delay);
if (autoClick3 == true)
setInterval(clickIncrement, delay);
if (autoClick4 == true)
setInterval(clickIncrement, delay);
if (autoClick5 == true)
setInterval(clickIncrement, delay);
if (autoClick6 == true)
setInterval(clickIncrement, delay);
if (autoClick7 == true)
setInterval(clickIncrement, delay);
if (autoClick8 == true)
setInterval(clickIncrement, delay);
if (autoClick9 == true)
setInterval(clickIncrement, delay);
}
}
//code buffs
function clickIncrement() {
clicks++;
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
function display() {
document.getElementById('output').innerHTML = clicks;
}
<!doctype html>
<html>
<head>
<title>Cookie Clicker (WIP)</title>
<script>
//alert("Please click the cookie first as there is an issue with a segment of the code. Do not hack. It makes the game not fun.");
</script>
</head>
<body>
<input class="tooltip" id="clickMe" type="image" src="" onclick="doFunction();" />
<br>
<h2>Clicks:</h2>
<p id="output"></p>
<h2 align="center">Perks</h2>
<input title="Doubles Mouse Clicks
Cost:250" class="tooltip" id="Cursors" type="image" src="" width="150" onclick="doFunction();" />
<br>
<h2>Items</h2>
<input id="AutoClicker" title="Buy The Autoclicker For 250 Clicks! Clicks once every second!" type="image" src="https://www.macupdate.com/images/icons256/50547.png" width="150" onclick="doFunction();" />
<br>
<h2>Item Upgrades:</h2>
<input id="moreAutoC" type="image" src="" title="More Autoclickers! (MAX:11)" onclick="doFunction();" />
</body>
</html>
I thought it would instantly make the button disappear, and then that would be the end of it. I didn't know there would be other stuff involved. Note: all the src tags are removed due to them being VERY long.
If you wanna remove the button & not just hide it, without jquery, you'll use an event argument from the onclick handler;
event.target.parentNode.removeChild(event.target);
Make an id of button as example id="btn"
Put on click of the code below
And use following code
function hide(){
document.getElementById("btn").style.display = "none";
}
Your question is a little unclear and there is a lot of code, it is not obvious which button you want to delete. As such I'll give you a generic answer that hopefully you will be able to apply.
//Will just hide the button
document.getElementById("willHide").addEventListener("click", function(event){
event.target.style.display = "none";
});
//Will remove the button from the DOM entirely
document.getElementById("willDelete").addEventListener("click", function(event){
event.target.parentNode.removeChild(event.target);
});
//Will disable the button
document.getElementById("willDisable").addEventListener("click", function(event){
event.target.disabled = true;
});
<input type="button" id="willHide" value="I will be hidden" />
<input type="button" id="willDelete" value="I will be deleted" />
<input type="button" id="willDisable" value="I will be disabled" />

Boolean value doesnt change

My JS code:
var name_valid = false;
$("#InputName").blur( function(){
if ($(this).val() != ""){
name_valid = true;
} else {
name_valid = false;
}
});
if (name_valid === true){
alert('ok');
}
console.log(name_valid);
I don't actually understand why my code is not working.
If my <input> is not empty I have to get alert ('ok'), but I don't get anything.
Why my boolean value is still false at the end?
Because it's a callback function, which executes only after the blur function is complete. This means that this line if (name_valid === true) is executing before this line if ($(this).val() != "").
Try changing your code to this:
var name_valid = false;
$("#InputName").blur( function(){
if ($(this).val() != ""){
name_valid = true;
} else {
name_valid = false;
}
if (name_valid === true){
alert('ok');
}
console.log(name_valid);
});
You made a little mistake, you should put your last if statement inside callback function, like below:
var name_valid = false;
$("#InputName").blur(function () {
if ($(this).val() !== "") {
name_valid = true;
} else {
name_valid = false;
}
if (name_valid === true) {
alert('ok');
}
console.log(name_valid);
});
Your conditional only runs on page load. You want it inside the event handler so it runs when the event actually gets triggered
var name_valid = false;
$("#InputName").blur(function() {
if ($(this).val() != "") {
name_valid = true;
} else {
name_valid = false;
}
if (name_valid === true) {
alert('ok');
}
console.log(name_valid);
});
var name_valid = false;
$("#InputName").blur( function(){
if ($(this).val() !== ""){
name_valid = true;
}
if (name_valid === true){
alert('ok');
}
console.log(name_valid);
});
Please try this.
$(document).ready(function () {
var name_valid;
$("input").blur(function () {
if ($(this).val() != "") {
name_valid = true;
} else {
name_valid = false;
}
if (name_valid) {
alert('ok');
}
});
});

JS in page head section isn't excecuting

I have a script that handles a semi-complex contact form. The site is built using a website building platform called Duda and I think there may be timing issues as they load a bunch of scripts of their own. Anyway I'm getting a ReferenceError: price is not defined, error.
Price gets called onChange on inputs, for example:
<input value="Yes" name="dmform-9" type="radio" id="watch-me-hide" checked="checked" onchange="price()"/>
The script works sometimes, then other times not. Very frustrating. Does anyone know how to make sure that my functions get loaded in this situation?
Here is the whole script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var counter = 0;
$(document).ready(function() {
$("input[type="radio"]").click(function() {
alert("here");
var ids = ["#occupiedBy", "#nameOccupied", "#phoneOccupied", "#mobileOccupied", "#emailOccupied"];
if($(this).attr("id") == "watch-me-hide" || $(this).attr("id") == "watch-me-show") {
if ($(this).attr("id") == "watch-me-hide") {
$("#show-me").hide();
ids.forEach((id) => $(id).prop("required", false));
}
else if ($(this).attr("id") == "watch-me-show"){
$("#show-me").show();
ids.forEach((id) => $(id).prop("required", true));
}
else {
}
} else if($(this).attr("id") == "hideShowInDepth-hide" || $(this).attr("id") == "hideShowInDepth-show") {
if ($(this).attr("id") == "hideShowInDepth-hide") {
$("#moreRooms").hide();
price(null);
ids.forEach((id) => $(id).prop("required", false));
}
else if ($(this).attr("id") == "hideShowInDepth-show"){
$("#moreRooms").show();
price(null);
ids.forEach((id) => $(id).prop("required", true));
}
}
else{
}
});
};
function price() {
var priceIncrement = 70;
var minimumPrice = "189.00";
var basic = document.getElementById("hideShowInDepth-hide");
var advanced = document.getElementById("hideShowInDepth-show");
var ids = ["numberAdditionalRooms", "numberLaundries", "bedrooms", "numberLounges", "numberDining", "numberKitchens", "numberBathrooms", "numberHallways", "numberGarages"];
if ((basic.checked == true) && (advanced.checked == false)) {
/* Get number of rooms for basic inspection */
var e = document.getElementById("bedrooms");
var numberOfBedrooms = e.options[e.selectedIndex].value;
if (numberOfBedrooms == 0){
document.getElementById("totalPrice").textContent = "0.00";
}
else if ((numberOfBedrooms <= 3) && (numberOfBedrooms >= 1)){
document.getElementById("totalPrice").textContent = minimumPrice;
}
else if ((numberOfBedrooms <= 6) && (numberOfBedrooms >= 3)){
document.getElementById("totalPrice").textContent = "259.00";
}
else if (numberOfBedrooms > 6){
document.getElementById("totalPrice").textContent = "329.00";
}
else {
alert("Script error: Undefined number of bedrooms")
}
return false;
}
else if ((basic.checked == false) && (advanced.checked == true)) {
/* Get number of rooms for advanced inspection */
ids.forEach(logArrayElements);
if (counter == 0){
document.getElementById("totalPrice").textContent = "0.00";
}
else if (counter == 1){
document.getElementById("totalPrice").textContent = minimumPrice.toFixed(2);
;
}
else {
var money = ((counter * priceIncrement) + +minimumPrice) - +priceIncrement;
document.getElementById("totalPrice").textContent = money.toFixed(2);
}
counter=0;
return false;
}
else if ((basic.checked == false) && (advanced.checked == false)) {
alert("Script error: Neither checkbox is checked");
return false;
}
else if ((basic.checked == true) && (advanced.checked == true)) {
alert("Script error: Both checkboxes are checked");
return false;
}
else{
alert("Script error: Unknown error");
return false;
}
}
function logArrayElements(element, index, array) {
// alert("a[" + index + "] = " + element + " - " + value);
var e = document.getElementById(element);
var strUser = e.options[e.selectedIndex].value;
counter = +counter + +strUser;
}
</script>
watch-me-hide and watch-me-show are radio buttons that when changed they hide or show another section of the contact form to fill out, and make the inputs required or not.
hideShowInDepth-hide and hideShowInDepth-show are the same, but for another div section.
the price function updates the text in a span to reflect a new price when an input value has changed.
price() gets called onchange of dropdowns and radio buttons.
Any help appreciated.

JS function working fine in debugger but not working without debugger

This JavaScript function is working fine when I execute it through the debugger, but when I am not using the debugger, it's not executing:
function setColumnDisabled(){
var activeGrid = null;
var activeTab = tabbar1.getActiveTab();
if (activeTab == "a1") {
activeGrid = genInfo.mygrid;
}else if (activeTab == "a2") {
activeGrid = genInfo.mygrid2;
} else if (activeTab == "a21") {
activeGrid = genInfo.mygrid3;
} else if (activeTab == "a22") {
activeGrid = genInfo.mygrid3;
}else if(activeTab == "PartialTunnels"){
activeGrid = genInfo.partialObjectsGrid;
}
if(activeGrid != null){
activeGrid.forEachRow(function(row_id){
activeGrid.cellById(row_id,activeGrid.getColIndexById("Shared")).setDisabled(true);
});
}
}

Javascript Focus Is Not Working on Aspx Page

Hy Guys,
Please Look at the code and Try to Help Out. The function ive written is not working but its RUNNING properly. Its about To set focus on next content on page im using it on an ASPX page. Heres my code Below :
function SetFocusOnSave(CTag,NTag)
{
alert('Running'+CTag+NTag);
var CurrentTag=document.getElementById(CTag);
var NextTag = document.getElementById(NTag);
if ( (event.keyCode==13)||(event.keyCode==9) )
{
if(CurrentTag.value=="")
{
alert("Please Enter Detail First");
CurrentTag.focus();
}
if(CurrentTag.value!="")
{
event.returnValue=true;
document.getElementById(NextTag).focus();
}
}
}
snametxt.Attributes.Add("onkeypress",
SetFocusOnSave('<%=snametxt.ClientID%>','<%=sdesctxt.ClientID%>');");
have you tried to replace
document.getElementById(NextTag).focus();
with
NextTag.focus();
?
You have to add return false; after you found the false in validation otherwise the flow will continue till end.
Try this function:
function SetFocusOnSave(CTag, NTag) {
alert('Running' + CTag + NTag);
var CurrentTag = document.getElementById(CTag);
var NextTag = document.getElementById(NTag);
if ((event.keyCode == 13) || (event.keyCode == 9))
{
if (CurrentTag.value == "")
{
alert("Please Enter Detail First");
CurrentTag.focus();
return false;
}
if (CurrentTag.value != "") {
event.returnValue = true;
NextTag.focus();
return false;
}
}
};
Hy Guys Ive Tried A NEW CODE AND Fortunately Its Working Fine Here its my Code
function Navigation(CTag, NTag, Number) {
var CurrentTag = document.getElementById(CTag);
var NextTag = document.getElementById(NTag);
var IsNumber = Number; //Checking if value is number
if (NextTag.disabled == true) {
NextTag.disabled = false;
NextTag.className = "txt";
}
if (event.keyCode == 9) {
CurrentTag.focus();
event.returnvalue = false;
}
if (event.keyCode != 9) {
if (event.keyCode == 13) {
if (IsNumber == "Y") {
if (NextTag.disabled == true) {
NextTag.disabled = false;
}
if (CurrentTag.value != "") {
NextTag.focus();
event.returnvalue = true;
}
if (CurrentTag.value == "") {
alert('Please Enter Value To Proceed Further.');
CurrentTag.focus();
event.returnvalue = false;
}
if (isNaN(CurrentTag.value)) {
alert("Please Enter A Valid Number");
CurrentTag.value = "";
CurrentTag.focus();
}
}
if (IsNumber == "N") {
if (CurrentTag.value == "") {
alert('Please Enter Value To Proceed Further.');
CurrentTag.focus();
event.returnvalue = false;
}
if (CurrentTag.value != "") {
NextTag.focus();
event.returnvalue = true;
}
}
}
}
};
Thanks ya'll !! :)

Categories

Resources