Change variable value on button click - javascript

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();
}
}

Related

I have a problem with if statement in javaScript

I want to check if the state of show to change the innerText of the button according to it but when I run it the else statment doesnt work
let showBtn = document.querySelector('.show-more');
showBtn.onclick = function () {
let show = false;
if (show === false) {
showBtn.innerText = 'Show Less';
show = true;
} else {
showBtn.innerText = 'Show more';
}
}
showBtn is false on each click in your code. It should not be assigned in the onclick handler. Try this:
let showBtn = document.querySelector('.show-more');
let show = false;
showBtn.onclick = function() {
if (show === false) {
showBtn.innerText = 'Show Less';
} else {
showBtn.innerText = 'Show more';
}
show = !show;
}
<button class="show-more" />Show</button>
Reset the value of show, every click by this way.
let showBtn = document.querySelector('.show-more');
show = false;
showBtn.onclick = function () {
if (show === false) {
showBtn.textContent= 'Show Less';
show = true;
} else {
show = false
showBtn.textContent= 'Show more';
}
}
You should not even be using a variable here in the first place. The accepted answer just creates a new bug as it will break as soon as you have more then one element as the global state would apply to all the elements.
If you want to attach state to elements you can either do it by adding/removing classes or through data attributes (or whatever more specific attribute is applicable).
let showBtn = document.querySelector('.show-more');
showBtn.onclick = function (event) {
// event.target is the clicked element
if (event.target.matches('.expanded')) {
showBtn.textContent= 'Show Less';
else {
showBtn.textContent= 'Show more';
}
event.target.classList.toggle('expanded')
}
In this example the class 'expanded' is used to keep track of the state of the button. This also lets you attach different visual "states" through CSS.
In this case do not assign your state variable let show inside of the calling function. When you do that it will initialize the variable every time you call it. This causes a performance issue (see variable initialization and garbage collection) and depending on what you want to do it will break.
Someone here as already given an answer, but in their answer the variable declaration is in global scope. Most people agree that it's not a good idea to declare global variables, especially with such a general name as show . Later on, as your code base grows, you're likely to run into conflicts and your code will start acting in ways you can't predict. This is probably the most universally agreed upon coding convention. It's a bad habit. Learn how to do it the right way now.
These two StackOverflow answers contain examples that are a good starting point to producing working modular code to control the state of your objects:
wrapper function: https://stackoverflow.com/a/50137216/1977609
This is another way to implement your button: https://stackoverflow.com/a/10452789/1977609

Click to enlarge image, then click again to make it go back to previous size

I want to be able to click on an image, have it become big, and then when I click it again, make it go back to being small. I'm trying to use an if/else statement to solve this problem, but I still can't figure it out. This is the JS I have so far:
document.addEventListener("DOMContentLoaded", function(event) {
var thumbnailElement = document.getElementById("smart_thumbnail");
if (thumbnailElement.className === "small") {
thumbnailElement.addEventListener("click", function() {
thumbnailElement.className = "";
});
} else {
thumbnailElement.addEventListener("click", function() {
thumbnailElement.className = "small";
});
}
});
And the HTML for the image:
<img class="small" id="smart_thumbnail" src="http://4.bp.blogspot.com/-QFiV4z\
3gloQ/ULd1wyJb1oI/AAAAAAAAEIg/LE1Kakhve9Y/s1600/Hieroglyphs_Ani-papyrus.jpg">
I'm simply wanting to get rid of the "small" class on the id "smart_thumbnail" to make it big and put the "small" class back to make it small again, but I can only make it big. When I click on it the 2nd time, it doesn't do anything. I've tried an if/else if statement and that didn't work. I looked on here for the same question, but could only find stuff about jQuery. Trying to solve this with JavaScript only.
Any help greatly appreciated. Thanks!
The problem is that the code above will only be run once: After loading your site. So only one condition is fullfilled (thumbnailElement.className === "small")
What you want is something along the lines of:
var thumbnailElement = document.getElementById("smart_thumbnail");
thumbnailElement.addEventListener("click", function() {
if (this.className === "small")
this.className = "";
else
this.className = "small";
});
This will check the class when clicking the image.
Alternatively, you can also use classList.toggle
The DOMContentLoaded event only fires once, that is, when the page is loaded. Instead run your if-statement on a per-click basis.
For example
thumbnailElement.addEventListener("click", function() {
if (thumbnailElement.className === "small") {
thumbnailElement.className = "";
} else {
thumbnailElement.className = "small";
}
});
Now you will register the click event once, but every time it is clicked it will check the classname logic and apply the class name appropriately.

Javascript function if statement not excuted right

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.

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.

Disable Select based on another element on the Same Row

In a table, I have a row with two inputs - one select and one text. What I want to achieve is that if one has a value, then the other (on the same row) should disable. This works correctly onload when there is a value in the textbox, but doesn't seem to work when there is a value in only the select box.
As you can see in the example here: http://jsfiddle.net/anAgent/UBUhn/1/ the "change" event works correctly, but it doesn't work onload.
Any help would greatly be appreciated!
I'm working with jQuery 1.5.2 and with both Google Chrome and IE9
Update With Final Code
Thanks #scoopseven and #eicto for your input. Based on these two answers, here's the final code. I hope it helps someone else.
$(document).ready(function() {
$(".validation-compare").change(runRowValidation);
$(".validation-compare").each(runRowValidation);
});
function runRowValidation() {
var $me = $(this),
$other = $('.validation-compare',$me.closest("tr")).not($me),
mVal = $me.val(),
oVal =$other.val();
if(mVal != "" && oVal == "") {
$me.removeAttr('disabled');
$other.attr('disabled',1);
} else if(mVal == "" && oVal != "") {
$other.removeAttr('disabled');
$me.attr('disabled',1);
} else {
$other.removeAttr('disabled');
$me.removeAttr('disabled');
}
}​
You can see it in action at: http://jsfiddle.net/anAgent/UBUhn/24/
i don't think that you you need to set the class valid, all you have to do is replacing
var $otherInput = $('.validation-compare', $parent).not('.valid');
by
var $otherInput = $('.validation-compare', $parent).not($me);
And this will resolve your problem on onload. Here is an example
var validme=function() {
var me=$(this);
me.removeClass('validation-compare');
if (me.val()) {
console.log(me);
me.addClass('valid');
me.parent().parent().find('.validation-compare').attr('disabled',1);
me.addClass('validation-compare');
return;
}
me.removeClass('valid');
if (me.parent().parent().find('.validation-compare.valid').length<1) {
me.parent().parent().find('.validation-compare').removeAttr('disabled'); }
me.addClass('validation-compare');
}
$('.validation-compare').each(validme);
$('.validation-compare').change(validme)
http://jsfiddle.net/UBUhn/22/
You need to separate out the function and call it on the click event and on page load. Something like this:
jQuery(function($){
function myFunction() {
// do somestuff
}
// myFunction needs to be called when select is clicked and when page is loaded
$('#someelement').click(myFunction);
$(document).ready(myFunction);
});

Categories

Resources