Multiple If Statements Cancelling each-other out? (Javascript) - javascript

I've been having some trouble with a piece of code that requires multiple lines of "if" logic to handle the functionality.
two of these if statements do the same thing, and it seems to me are some how cancelling each other out.
function visibleCheck() {
var target = document.getElementById('contentType').val();
if (target != "BYOC - Document to Exam") {
document.getElementById('VideoMinutes').style.display = 'block';
}
else document.getElementById('VideoMinutes').style.display = 'none';
if ((target != "Custom Production - Avatar") {
document.getElementById('Questions').style.display = 'block';
}
else document.getElementById('Questions').style.display = 'none';
if ((target != "Custom Production - Video") {
document.getElementById('Questions').style.display = 'block';
}
else document.getElementById('Questions').style.display = 'none';
}
The First if statement runs fine. The second doesn't appear to run at all. The third one runs fine.
If I re-order the second and third one swapping places, the new second one will not work.
If I use the or operator "||" and combine the statements it doesn't work at all.
The third statement always works regardless of the conditions for the if statement.
If I make the second and third both if or statements then neither work.
Any ideas?
I am using this on a visualforce page within salesforce if that makes any difference.

Firstly, note that DOMElements do not have the val() method, that's only on jQuery objects. You should use the value property.
Secondly, the logic is flawed as the execution for the Questions elements can flow through multiple contradicting conditions. Try this:
function visibleCheck() {
var target = document.getElementById('contentType').value;
if (target != "BYOC - Document to Exam") {
document.getElementById('VideoMinutes').style.display = 'block';
}
else {
document.getElementById('VideoMinutes').style.display = 'none';
}
if (target != "Custom Production - Avatar" && target != "Custom Production - Video") {
document.getElementById('Questions').style.display = 'block';
}
else {
document.getElementById('Questions').style.display = 'none';
}
}
As you've tagged this with jQuery, here's a simplified jQuery version:
function visibleCheck() {
var target = $('#contentType').val();
$('#VideoMinutes').toggle(target != 'BYOC - Document to Exam');
$('#Questions').toggle(target != "Custom Production - Avatar" && target != "Custom Production - Video");
}

Related

Why doesn't the removeChild remove the element?

I have written this scrip to take out ads on a website. Was working on it the whole day.
This is the JS code:
var timer = setInterval(deletor, 1);
function deletor() {
timer;
var slider = document.querySelector("#slider-con");
var bannerTop = document.querySelector("#MainContent > div:nth-child(2)")
var bannerMiddle = document.querySelector("#MainContent > iframe");
var bannerRandom = document.querySelector("#MainContent > div:nth-child(7)");
var bannerRandom2 = document.querySelector("#MainContent > div:nth-child(6)");
if (slider == undefined) {
return false;
} else {
slider.parentNode.removeChild(slider);
};
if (bannerTop == undefined) {
return false;
} else {
bannerTop.parentNode.removeChild(bannerTop);
};
if (bannerMiddle == undefined) {
return false;
} else {
bannerMiddle.parentNode.removeChild(bannerMiddle);
};
if (bannerRandom == undefined) {
return false;
} else {
bannerRandom.parentNode.removeChild(bannerRandom);
};
if (bannerRandom2 == undefined) {
return false;
} else {
bannerRandom2.parentNode.removeChild(bannerRandom2);
};
};
Now, as you can see, it gets the values first and then goes through if statements. Idea behind this is: On first try, it deletes the elements and on the second one, it stops the function.
But when I inserted this last element, it won't delete it. The ID is correct, everything is correct but it won't delete the element, so I keep getting the same alert over and over.
Also, I found out that, I get this banner ad on two places. When I have "var bannerRandom = document.querySelector("#MainContent > div:nth-child(7)");" this, it appears as "document.querySelector("#MainContent > div:nth-child(6)")" this, and when I have both, it appears as "document.querySelector("#MainContent > div:nth-child(6)")" this. And it's not deleted.
Console shows no errors.
Your various statements in the form:
if (slider == undefined) {
return false;
} else {
slider.parentNode.removeChild(slider);
};
mean this: "If slider wasn't found in the DOM, exit the function. Otherwise, remove the slider and continue the function."
So that means your function will terminate the first time one of the elements you're looking for doesn't exist. Since it terminates then, none of the other elements after it is checked. That seems unlikely to be what you want to do.
You probably just wanted:
if (slider) {
slider.parentNode.removeChild(slider);
}
...and so on.
Note that you don't put ; at the end of a block attached to a flow-control statement like if or else, which is why I've removed it above. (Doing so is harmless, because JavaScript ignores them; but it's pointless.)

How to make this jQuery code work on version 3.2.1

I have a function which can download free resource and apply or modify my work. I used this function to make my website by setting all divs to display=none and with clicking on a button, the corresponding div display style will become block.
Everything was working fine until I add a music player that the creator use higher jQuery library (3.2.1 > 1.5.2).
Everything works great like before, but when I click on button to play the music, I can't go back or go to other menus.
Debugger error is :
uncaught TypeError: document.getElementById is not a function
But if I don't click on play button, everything is normal.
function openPage(pageName) {
var i;
var x = document.getElementsByClassName("page");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
document.getElementById(pageName).style.display = "block";
}
Jquery does not prevent vanilla Javascript from running normally.
And as your code is simply Javascript, and from what it appears there are no mistakes within it, it's hard to figure out why such an error would appear. This has nothing to do with Jquery.
The only foreseeable error would be:
pageName is not passed as an argument;
pageName is passed, but is not a string;
no element with the id equal to the pageName's value exists within your document.
You could slightly improve your code by writing it in this way:
function openPage(pageName) {
Array.from(document.getElementsByClassName('page')).map(page => page.style.display = 'none');
document.getElementById(pageName).style.display = "block";
};
You could make it 'more fullproof' by adding some checks:
function openPage(pageName) {
if (pageName && (typeOf pageName === 'string')) {
Array.from(document.getElementsByClassName('page')).map(page => page.style.display = 'none');
var target = document.getElementById(pageName);
if (target) { target.style.display = "block" };
}
};
And yu could improve it by also loggin to the console, when a check has failed, for debugging:
function openPage(pageName) {
if (pageName && (typeOf pageName === 'string')) {
Array.from(document.getElementsByClassName('page')).map(page => page.style.display = 'none');
var target = document.getElementById(pageName);
if (target) {
target.style.display = "block"
} else {
console.log('No element found, with the ID of:' , pageName)
};
} else {
console.log('Error in openPage() : The provided [pagename] argument must be a [string]. Provided value for [pageName] is:', pageName);
}
};

Javascript click event requires double clicks

I have a simple HTML-CSS-JavaScript page with an event listener on a button to toggle a div.
However, all is working but the animation function takes two clicks first time to work, although i consoled the click event to prove that the button listens to the first click too.
i tried to wrap into window.onload but same thing.
note: i want to use pure javascript only.
thank you
this pic shows the first click (it says "clicked" in the console):
this pic shows the second click (animation took place):
Here is my code:
var showDivButton = document.getElementById('showDivButton');
var info = document.getElementById('info');
showDivButton.addEventListener('click', animation) ;
// animation func
function animation () {
console.log('Clicked!');
if (info.style.display === 'none'){
info.style.display = 'inline-block';
showDivButton.style.background = 'green';
} else {
info.style.display = 'none';
showDivButton.style.background = 'gray';
}
}
Look at My Plunker Here please. Thank you in advance.
Try to revise your function block as follow:
function animation () {
console.log('Clicked!');
if (info.style.display == '' || info.style.display == 'none'){
info.style.display = 'inline-block';
showDivButton.style.background = 'green';
} else {
info.style.display = 'none';
showDivButton.style.background = 'gray';
}
}
info.style.display is '' on initial
Because info.style.display refers to the style attribute of your div, not the computed Style, so on the first click, this is not set.
You may want to look at getComputedStyle, but i would advise switching class instead of directly modifying style.

Uncaught ReferenceError: parentsCheck is not defined

I am very new to JS, but am trying to create a checkbox that when checked will reveal a div with an id of "second_row", and when unchecked will hide it (unchecked by default). Am I missing some code? Is my syntax incorrect? I could really use some help. Thanks for givin a newbie a hand!
Html:
<input type="checkbox" name="under_18" id="under_18" class="check" value="under_18" form="contest_form" onclick="parentsCheck()" />
JavaScript:
<script>
function parentsCheck()
{
var check1 = document.getElementById('under_18'),
if (check1.checked === true) {
document.getElementById('second_row').style.display = 'block';
}
else if (check1.checked === false) {
document.getElementById('second_row').style.display = 'none';
}
}
</script>
P.S. Dont know if it matters, but the checkbox is in a table cell.
Your , at the end of the var statement should be a ;.
It's causing a SyntaxError, causing the JavaScript block to be effectively ignored, so parentsCheck() is never defined.
var check1 = document.getElementById('under_18');
http://jsfiddle.net/tYv28/
As an aside, check1.checked will always return a boolean, so you don't need to do the === true and === false comparison; the following will work just fine:
function parentsCheck()
{
var check1 = document.getElementById('under_18');
if (check1.checked) {
document.getElementById('second_row').style.display = 'block';
} else {
document.getElementById('second_row').style.display = 'none';
}
}
When using event handler attributes, JavaScript only recognizes functions in the global scope. Try defining the event handler in your JavaScript, which also has the benefit of being unobtrusive:
var el = document.getElementById('under_18');
el.onclick = parentsCheck; // <---- This
jsFiddle
Also, you need to change the , into a ;.

Javascript execute once

How do i get a javascript code to only execute or be used once? example is
var stringToMatch = 'christopher';
function toggle (){
var input = document.getElementById('text').value;
if (input == stringToMatch){
document.getElementById('divColor1').style.display = 'block';
}
else {
document.getElementById('divColor1').style.display = 'none';
}
}
this code or stringToMatch i want to execute once, after that i dont care if it is deleted in the sense. for this is for coupons. and i am making multiples of this, so once someone has typed this i want it to delete
If I got you right, you could overwrite toggle() with an empty function.
if (input == stringToMatch){
document.getElementById('divColor1').style.display = 'block';
window.toggle = function() { };
}

Categories