HTML / Javascript - Trouble changing text when clicked - javascript

So I have some HTML code here:
<body>
<b style="font-size: 26px;">How the game works</b>
<u id="HowToPlay_HideShow" style="color: #9FF;">[hide]</u><br>
</body>
And I also used Javascript to turn the hide text into show, and show back into hide when clicked on.
<script>
var HowGameWorks_Hidden = false;
document.getElementById("HowToPlay_HideShow").onclick = function () {
if (HowGameWorks_Hidden == false) {
document.getElementById("HowToPlay_HideShow").innerHTML = "[show]";
HowGameWorks_Hidden = true;
}
if (HowGameWorks_Hidden == true) {
document.getElementById("HowToPlay_HideShow").innerHTML = "[hide]";
HowGameWorks_Hidden = false;
}
}
</script>
This, however, does not seem to work. Clicking on the hide and show text has no effect at all. So I tried removing this piece of code:
if(HowGameWorks_Hidden == true) {
document.getElementById("HowToPlay_HideShow").innerHTML = "[hide]";
HowGameWorks_Hidden = false;
}
And it correctly turns the hide text into show when I click it (but, of course, does not turn the show text back into hide).
So how do I get my code working?

This is because your second if statement will always get triggered if your first one does, since you set HowGameWorks_Hidden to true in it. You need to use an else:
if(HowGameWorks_Hidden == false) {
document.getElementById("HowToPlay_HideShow").innerHTML = "[show]";
HowGameWorks_Hidden = true;
}
else if(HowGameWorks_Hidden == true) {
document.getElementById("HowToPlay_HideShow").innerHTML = "[hide]";
HowGameWorks_Hidden = false;
}

Related

javascript that hides/shows element based on criteria not working with style.display = "none"

I have this section of javascript in my html that grabs a form input, puts it through a function and returns a json. I then want to either hide or show certain form elements based on the values in this json.
At the moment, i can do all of this fine except for changing the style.display properties of the elements im trying to hide/show, i can find them okay with getElementbyId (have tested this with other stuff) but the changes i make to the style don't seem to do anything.
As you can see below, i have put in a few alerts to make sure everything is working, and they all seem to align with what i need from the function. The alert showing style.display even matches up with what i'm trying to change it to, however even if it says "none", the form element still shows up.
<script type="text/javascript">
let selected = document.getElementById('selection1');
let optional_toggle = document.getElementById("optional_element");
let button = document.getElementById("button")
button.onclick = function() {
choice1 = selected.value;
fetch('/form_choice/' + choice1).then(function(response) {
response.json().then(function(data) {
if (data.show_optional === "True") {
optional_toggle.style.display = ""
window.alert("first part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
}
else {
optional_toggle.style.display = "none"
window.alert("second part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
console.log(optional_toggle);
}
}
)
}
)
}
</script>
Edit: i added the console.log lines in but nothing seems to show in the console.
console log image
The issue was that the page was reloading to it's original state after the script had been executed, so i stopped this by adding "; return false" after the function like so:
<script type="text/javascript">
let selected = document.getElementById('selection1');
let optional_toggle = document.getElementById("optional_element");
let button = document.getElementById("button")
button.onclick = function() {
choice1 = selected.value;
fetch('/form_choice/' + choice1).then(function(response) {
response.json().then(function(data) {
if (data.show_optional === "True") {
optional_toggle.style.display = ""
window.alert("first part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
}
else {
optional_toggle.style.display = "none"
window.alert("second part of if");
window.alert(optional_toggle.style.display);
window.alert(data.show_optional);
console.log(optional_toggle);
}
}
)
}
); return false
}
</script>

Why does jQuery click event only work once?

I am trying make speed units toggle when clicking. However, this only works once. I have run out of things to try. I also tried .click(), .live(), .toggle() (which only made it disappear and reappear), etc.
HTML:
<li id="wind">Wind speed</br>
<p class='windSpeedKm'></p>
</li>
Javascript:
var click = true;
$('#wind').on('click', function() {
if (click = false) {
$('#wind').html(function() {
$(this).html("Wind speed<br>" + windKm);
click = true;
});
} else if (click = true) {
$('#wind').html(function() {
$(this).html("Wind speed<br>" + windMi);
click = false;
});
}
});
This isn't exactly what you asked for, but this will save you so much time it is unbelievable. It has an auto convert function built in so you don't have to manually update both numbers. It doesn't replace unnecessary to replace html.
<li id="wind">Wind speed</br>
<p class='windSpeedKm' km="500">500</p>
</li>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function toMiles(km) {
return parseFloat(km) * 0.62137;
}
$('#wind').on('click', function() {
console.log($(this).attr("km"));
windSpeedKm = $(this).find(".windSpeedKm");
km = windSpeedKm.attr("km");
if (km === windSpeedKm.html()) {
windSpeedKm.html(toMiles(km));
} else {
windSpeedKm.html(km);
}
});
</script>
There are a few syntax issues with the code:
var click = true;
$('#wind').on('click', function() {
if (click) {
$(this).html("Wind speed<br>" + windKm):
click = true;
} else {
$(this).html("Wind speed<br>" + windMi);
click = false;
}
});
Note: there isn't any need to set click = true or click = false in your example as falling into the if statement by checking the click assignment value, this will already be true! You would only do this if you wanted to toggle the boolean to false after confirming it was true.
click = true should be click == true;

Jquery stop the first clicked button from executing the same code

My issue seems like it would be on here already but I just can't find it. Apologies in advance!!!!
After clicking one of multiple (unique) buttons, the initial corresponding div selected keeps executing even when clicking a different button.
How can I stop the first clicked button from executing the same code?
HTML
<button id="freeButton" type="button">Redeem</button>
<button id="giftCardButton" type="button">Redeem</button>
Jquery
content[0] = content;
content[1] = other content;
$(freeButton).click(function(){
if(!visible) {
$('#items').append(content[0]);
visible = true;
} else {
$('#items').remove(content[0]);
visible = false;
}
});
$(giftCardButton).click(function(){
if(!visible) {
$('#items').append(content[1]);
visible = true;
} else {
$('#items').remove(content[1]);
visible = false;
}
});
With this line $('#items').remove(content[1]); you are removing the element from the dom and with append you are not replacing the content of the div, you're just adding to it.
you need to use the html() methode instead.
var content = ["content", "other content"];
visible = false;
$('#freeButton').click(function(){
if(!visible) {
$('#items').html(content[0]);
visible = true;
} else {
$('#items').html("");
visible = false;
}
});
$('#giftCardButton').click(function(){
if(!visible) {
$('#items').html(content[1]);
visible = true;
} else {
$('#items').html("");
visible = false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="freeButton" type="button">Redeem1</button>
<button id="giftCardButton" type="button">Redeem2</button>
<div id="items"></div>

Need help in Javascript onChange event

On change of a dropdown value, I need to confirm whether the user wants to change the value or changed it by mistake.
If user clicks on OK then system should apply the modification, otherwise the value should not change.
As of now I have written code as follows:
document.getElementById("dropdownid").onchange = function (){
var a = confirm("Do you want to change");
if (a == true){
return true;
}
if (a == false){
return this;
}
}
here am getting the confirm box but regardless of whether if I press OK or Cancel, the dropdown always shows the new value.
check this fiddle
var drop = document.getElementById("dropdownid");
var selected =drop.options[drop.selectedIndex]; //save selection initially
drop.onclick = function (e){
selected = drop.options[drop.selectedIndex]; // save current selection
}
drop.onchange = function (e){
var a = confirm("Do you want to change");
if (a == false) // no need to check for true
{
selected.selected=true; // if cancel, set the existing selected option
}
}
Please try this:
document.getElementById("dropdownid").onchange = function (){
var a = confirm("Do you want to change");
if (a == true)
{
return true;
}
if (a == false)
{
return false;
}
}
You can undo the selection like this:
document.getElementById("dropdownid").onchange = function (){
if (!confirm("Do you want to change")) {
if (typeof this.prevVal=='undefined') {
this.prevVal=this.options[0].value;
for (var i=0;i<this.options.length;i++)
if (this.options[i].defaultSelected)
this.prevVal=this.options[i].value;
}
this.value=this.prevVal;
} else {
this.prevVal=this.value;
}
}
Basically you save in an attribute the previously selected value, and you search for the default value if not changed yet.
try using this code
document.getElementById("dropdownid").onchange = function (eve){
var a = confirm("Do you want to change");
if (a == true){
return true;
}
if (a == false){
eve.preventDefault();
}
}

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