Displaying div based on dropdown value - javascript

I have 3 divs each with a distinct id. Based off the value of a dropdown I have, I want to show one of the divs. I created my function and call it, but for some reason no change occurs. The new value of the dropdown is never recorded, when I use console.log. I am unsure what is causing the problem and would appreciate any help.
HTML
<div class="ins-left" id="fifteen">
<p>$15</p>
</div>
<div class="ins-left" id="thirty">
<p>$30</p>
</div>
<div class="ins-left" id="fourtyfive">
<p>$45</p>
</div>
CSS
#fifteen {
display: none;
}
#thirty {
display: none;
}
#fourtyfive {
display: none;
}
JS
var length = document.getElementById('length');
var chosenLength = length.options[length.selectedIndex].value;
var start = document.getElementById('start').innerHTML.split('.').join('').toLocaleLowerCase();
var end = document.getElementById('end').innerHTML.split('.').join('').toLocaleLowerCase();
var time = document.getElementById('time');
time.disabled = true;
function disabled() {
if (chosenLength.value != "") {
time.disabled = false;
}
}
var slotTimes = [];
document.getElementById("length").onchange = function (evt) {
var timeDistance = evt.target.value;
var startMoment = moment(start, "h:mm a");
var endMoment = moment(end, "h:mm a");
slotTimes = [];
while (startMoment.isSameOrBefore(endMoment)) {
slotTimes.push(startMoment.format("h:mm a"));
startMoment = startMoment.add(timeDistance, 'minutes');
}
addDropdown();
price();
};
function price(){
if (chosenLength.value === "") {
document.getElementById('fifteen').style.display = "none";
document.getElementById('thirty').style.display = "none";
document.getElementById('fourtyfive').style.display = "none";
}
if (chosenLength.value === "30") {
document.getElementById('fifteen').style.display = "block";
document.getElementById('thirty').style.display = "none";
document.getElementById('fourtyfive').style.display = "none";
}
if (chosenLength.value === "60") {
document.getElementById('fifteen').style.display = "none";
document.getElementById('thirty').style.display = "block";
document.getElementById('fourtyfive').style.display = "none";
}
if (chosenLength.value === "90") {
document.getElementById('fifteen').style.display = "none";
document.getElementById('thirty').style.display = "none";
document.getElementById('fourtyfive').style.display = "block";
}
}
function addDropdown() {
var doc = '',
times = slotTimes,
i;
for (i = 0; i < times.length; i++) {
doc += "<option value='" + times[i] + "'>" + times[i] + "</option>";
}
document.getElementById('time').innerHTML = doc;
disabled();
}

I made a simple working example for you here, so you can adjust your code based on this:
https://codepen.io/brunomont/pen/WmExvV
I had to remove a couple of broken references since your HTML didn't include everything (like the time elements). Also, make sure you have all the dependencies loading (I noticed you are using moment.js).
The changes I made were:
Adding a document.addEventListener("DOMContentLoaded", function() to make sure your HTML was loaded, before you tyr to run the JavaScript.
Change the way you bind your onChange function to be document.getElementById('length').addEventListener('change', function (evt)
Basically, the addEventListener is more flexible than onChange. You can read more about this change here:
addEventListener vs onclick
Hope it helps :)

Related

addEventListener to a class for hide and show toggle

var my_toggle = document.getElementsByClassName('my_toggle');
var my_toggle_button = document.getElementsByClassName('my_toggle_button');
var my_toggle_array = [];
var i;
for(i = 0; i < my_toggle.length; i++){
//my_toggle_array.push(0);
my_toggle[i].style.display = "none";
my_toggle_button[i].addEventListener("click", function(){
if(my_toggle[i].style.display == "none" /* || my_toggle_array[i] == 0 */){
my_toggle[i].style.display = "block";
my_toggle_button[i].innerHTML = "- show less";
//my_toggle_array[i] = 1;
} else {
my_toggle[i].style.display = "none";
my_toggle_button[i].innerHTML = "+ show more";
//my_toggle_array[i] = 0;
}
});
}
<div class="my_toggle">
<p class="lead"></p>
</div>
<button class="my_toggle_button"></button>
<!-- and so on 11 times <div class="my_toggle><p class="lead"></p></div><button class="my_toggle_button"></button> -->
This code doesn't work when I upload it in cPanel or at least not all of it, it works until these lines
for(i = 0; i < my_toggle.length; i++){
//my_toggle_array.push(0);
my_toggle[i].style.display = "none";
So basically the eventListener doesn't work, I tried like 2 hours in a script tag inside the page I wanted to do this toggle in but didn't work, then I put this code inside an external js file and I get like an error message "do not use functions inside a loop", why not using functions inside a loop?I commented out this code and used like this code which works but is way too long...
var my_toggle = document.getElementsByClassName('my_toggle');
var my_toggle_button = document.getElementsByClassName('my_toggle_button');
var my_toggle_id = [];
var my_toggle_button_id = [];
var i;
for(i = 0; i < my_toggle.length; i++){
my_toggle[i].setAttribute("id", "my_toggle_" + i.toString());
my_toggle_id.push("my_toggle_" + i.toString());
my_toggle_button[i].setAttribute("id", "my_toggle_button_" + i.toString());
my_toggle_button_id.push("my_toggle_button_" + i.toString());
}
function function1(){
let x = document.getElementById(my_toggle_id[0]);
let y = document.getElementById(my_toggle_button_id[0]);
if (x.style.display === "none") {
x.style.display = "block";
y.innerHTML = "- mostra di meno";
} else {
x.style.display = "none"; y.innerHTML = "+ scopri di più";
}
}
/* [...] and so on until */
function function11(){
let x = document.getElementById(my_toggle_id[10]);
let y = document.getElementById(my_toggle_button_id[10]);
if (x.style.display === "none") {
x.style.display = "block";
y.innerHTML = "- mostra di meno";
} else {
x.style.display = "none"; y.innerHTML = "+ scopri di più";
}
}
How can I add the EventListener to all classes without writing 130 lines of code?Is javascript the problem?Should I use PHP perhaps?Why?
The problem here is use of var.
The var statement declares a function-scoped or globally-scoped variable
Read about var and let
When you declare var i , increment it inside the loop to make it 1 and then click function is called, the value of i remains 1 and hence my_toggle[i] becomes undefined and my_toggle[i].style would throw an error "Cannot read property 'style' of undefined". Use let for your index i to keep it block scoped. See below code:
<!DOCTYPE html>
<head>
<title>The Alphabet</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="my_toggle">
<p class="lead">And so on 11 times</p>
</div>
<button class="my_toggle_button"></button>
</body>
<script type="text/javascript">
var my_toggle = document.getElementsByClassName('my_toggle');
var my_toggle_button = document.getElementsByClassName('my_toggle_button');
var my_toggle_array = [];
for(let i = 0; i < my_toggle.length; i++){
//my_toggle_array.push(0);
my_toggle[i].style.display = "none";
my_toggle_button[i].addEventListener("click", function(){
if(my_toggle[i].style.display == "none" /* || my_toggle_array[i] == 0 */){
my_toggle[i].style.display = "block";
my_toggle_button[i].innerHTML = "- show less";
//my_toggle_array[i] = 1;
} else {
my_toggle[i].style.display = "none";
my_toggle_button[i].innerHTML = "+ show more";
//my_toggle_array[i] = 0;
}
});
}
</script>
</html>

Whats wrong with me code (dom+onclick+li+display)?

Working
tutorial.onclick = function(){
var tutorial = document.getElementById("tutorials-ul");
tutorial.style.display = "list-item";
}
Not working
news.onclick = function(){
var news = document.getElementById("news-ul");
if(news.style.display == "none") {
news.style.display = "list-item";
}
else if(news.style.display == "list-item") {
news.style.display = "none";
}
}
Any answer or opinion is accepted.
I assume the outer news is a button that has already been assigned to a variable (or the default global via its ID).
The issue is if the element itself does not have a display set in its style attribute, then its initial value will be "" instead of whatever was given in CSS.
Therefore instead of comparing to "none", compare to "".
news.onclick = function() {
var news = document.getElementById("news-ul");
if (news.style.display == "") {
news.style.display = "list-item";
} else {
news.style.display = "";
}
}
#news-ul {
display: none
}
<button id=news>CLICK FOR NEWS</button>
<ul id="news-ul">
<li>TEST
</ul>
I figured it out using this stack overflow Get a CSS value with JavaScript
The correct code for showing and hiding the nested uls is
news.onclick = function(){
var news = document.getElementById("news-ul");
function compareDisplayValue(){
var element = document.getElementById("news-ul");
var style = window.getComputedStyle(element);
var display = style.getPropertyValue('display');
if(display == "none"){
news.style.display = "list-item";
}
else if (display == "list-item"){
news.style.display = "none";
}
}
compareDisplayValue();
}

Using Javascript Commands After Including Into Page

I have a page with three tables (Table A, Table B, Table C), which I want to display depending on which button the user clicks. I am able to do this just fine with the following script:
var tableA = document.getElementById("tableA");
var tableB = document.getElementById("tableB");
var tableC = document.getElementById("tableC");
var btnTabA = document.getElementById("showTableA");
var btnTabB = document.getElementById("showTableB");
var btnTabC = document.getElementById("showTableC");
btnTabA.onclick = function () {
tableA.style.display = "table";
tableB.style.display = "none";
tableC.style.display = "none"; }
btnTabB.onclick = function () {
tableA.style.display = "none";
tableB.style.display = "table";
tableC.style.display = "none"; }
btnTabC.onclick = function () {
tableA.style.display = "none";
tableB.style.display = "none";
tableC.style.display = "table"; }
However, I also want to include the html code for these tables into this page. I am also able to do this with the following script:
$(function(){ $("#include-tables").load("P1/1_0/table.html"); });
That said I cannot get these to work together. For example, when I combine all of this -- see sample code below -- my tables are included, but the buttons no longer work. If I check the error log in the browser, it says Null is not a object, and so I think the issue is to due with all variables and Id's being defined before the code for the button executes. That said with my (very) limited knowledge of javascript I am have not been able to figure out how to resolve this.
$(function(){
$("#include-tables").load("/1_0/tables.html");
});
var tableA = document.getElementById("tableA");
var tableB = document.getElementById("tableB");
var tableC = document.getElementById("tableC");
var btnTabA = document.getElementById("showTableA");
var btnTabB = document.getElementById("showTableB");
var btnTabC = document.getElementById("showTableC");
btnTabA.onclick = function () {
tableA.style.display = "table";
tableB.style.display = "none";
tableC.style.display = "none";
}
btnTabB.onclick = function () {
tableA.style.display = "none";
tableB.style.display = "table";
tableC.style.display = "none";
}
btnTabC.onclick = function () {
tableA.style.display = "none";
tableB.style.display = "none";
tableC.style.display = "table";
}
#tableA {
}
#tableB {
display: none;
}
#tableC {
display: none;
}
<div id="include-tables"></div>
<div class="button-div">
<input type="button" id="showTableA" value="TableA">
<input type="button" id="showTableB" value="TableB">
<input type="button" id="showTableC" value="TableC">
</div>
<script src="script.js"></script>
.load() is asynchronous, so you can't access the elements until after it completes. Put all your code in its callback function.
$(function(){
$("#include-tables").load("/1_0/tables.html", function() {
var tableA = document.getElementById("tableA");
var tableB = document.getElementById("tableB");
var tableC = document.getElementById("tableC");
var btnTabA = document.getElementById("showTableA");
var btnTabB = document.getElementById("showTableB");
var btnTabC = document.getElementById("showTableC");
btnTabA.onclick = function () {
tableA.style.display = "table";
tableB.style.display = "none";
tableC.style.display = "none";
}
btnTabB.onclick = function () {
tableA.style.display = "none";
tableB.style.display = "table";
tableC.style.display = "none";
}
btnTabC.onclick = function () {
tableA.style.display = "none";
tableB.style.display = "none";
tableC.style.display = "table";
}
});
});
Or you could use event delegation to bind event handlers to dynamically-added elements. See Event binding on dynamically created elements?

javascript webservice call and settimeout

i'm currently developing an application that relies on webservice calls in order to create a tree-like "menu", everything works as intended but i realized not all the target audience has a fast internet connection like i have right now on the development environment. my goal is to show a loading "screen" while the javascript function creates and then adds the elements to the DOM, the flowchart is as follows:
user click on the "expand" image of a node
user sees a div loading gif
user is presented with the childnodes
i'm not sure where i should put the timeout
my code:
...
elemento_tema_imagem_esconde_mostra.addEventListener("click", Get_Feat);
...
function Get_Feat(event) {
Tema_Expandido = event.target.parentNode;
if (typeof (Tema_Expandido.getElementsByTagName("ul")[0]) === "undefined") {
sMNID = event.target.parentNode.getElementsByTagName("a")[0].getAttribute("mnid");
var service = new WebJSON;
service.GetFeat(sMNID, SuccessCallback_Get_Feat, OnfailureCallback_Get_Feat);
} else {
//debugger;
var elemento = Tema_Expandido.getElementsByTagName("ul")[0];
var imagem_esconder_mostar = elemento.parentNode.childNodes[0];
var style = window.getComputedStyle(elemento, null);
if (style.display == "block") {
elemento.style.display = "none";
imagem_esconder_mostar.src = "Content/Images/img_abrir_22_22.png";
} else if (style.display == "none") {
elemento.style.display = "block";
imagem_esconder_mostar.src = "Content/Images/img_fechar_22_22.png";
}
}
};
function SuccessCallback_Get_Feat(Resultado_Get_Feat) {
var colleccao_Feat = JSON.parse(Resultado_Get_Feat);
var lista_feat = document.createElement("ul");
lista_feat.setAttribute("class", "lista-sem-bullets");
for (var i = 0; i < colleccao_Feat.length; i++) {
var elemento_feat = document.createElement("li");
var elemento_feat_imagem_esconde_mostra = document.createElement("img");
var elemento_feat_imagem_no = document.createElement("img");
var elemento_feat_link = document.createElement("a");
if (colleccao_Feat[i].FILHOS > 0) {
elemento_feat_imagem_esconde_mostra.src = "Content/Images/img_abrir_22_22.png";
elemento_feat_imagem_esconde_mostra.addEventListener("click", Get_Compo);
} else if (colleccao_Feat[i].FILHOS = 0) {
elemento_feat_imagem_esconde_mostra.src = "Content/Images/seta_dir_26_20.png";
}
//elemento_feat_imagem_esconde_mostra.addEventListener("click", Get_Feat);
//elemento_feat_imagem_no.src = "Content/Images/feat.png"
elemento_feat_link.setAttribute("FNID", colleccao_Feat[i].FNID);
elemento_feat_link.innerText = colleccao_Feat[i].NAMEDESC;
elemento_feat.appendChild(elemento_feat_imagem_esconde_mostra);
elemento_feat.appendChild(elemento_feat_imagem_no);
elemento_feat.appendChild(elemento_feat_link);
lista_feat.appendChild(elemento_feat);
};
document.getElementById("myModal_Loading").style.display = "none";
Tema_Expandido.appendChild(lista_feat);
Tema_Expandido.childNodes[0].src = "Content/Images/img_fechar_22_22.png";
};
function OnfailureCallback_Get_Feat(error) {
//displaying error on alert box
alert(error);
};
any help will be much appreciated

Replace image with different image/button - javascript

within a function, I'm trying to replace a image/button with another image/button.
<img src="images/14.gif" id="ImageButton1" onClick="showLoad()">
<img src="images/getld.png" id="ImageButton2" alt="Get Last Digits" style="display:none;" onClick="showLock()" />
<script type="text/javascript" language="javascript">
function swapButton(){
document.getElementById('ImageButton1').src = document.getElementById('ImageButton2').src;
}
</script>
But I have the problem that there is two of the same button, (button 2) when it is replaced! (one at the top of the page, and one where it is meant to be). I was wondering if there is a way of getting rid of the extra button at the top, or creating the button element within the javascript function?
Thanks for any help.
You can remove an element in javascript using
var el = document.getElementById('id');
var remElement = (el.parentNode).removeChild(el);
You can hide the first button, not only change the image source. The code below shows one way of doing that.
<img src="images/14.gif" id="ImageButton1" onClick="swapButtons(false)" style="visibility: visible;" />
<img src="images/getld.png" id="ImageButton2" alt="Get Last Digits" style="visibility: hidden;" onClick="swapButtons(true)" />
<script type="text/javascript" language="javascript">
function swapButtons(show1) {
document.getElementById('ImageButton1').style.visibility = show1 ? 'visible' : 'hidden';
document.getElementById('ImageButton2').style.visibility = show1 ? 'hidden' : 'visible';
}
</script>
I'd suggest something akin to the following:
function swapImageSrc(elem, nextElemId) {
if (!elem) {
return false;
}
if (!nextElemId || !document.getElementById(nextElemId)) {
var id = elem.id.replace(/\d+/, ''),
nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
next = document.getElementById(id + nextNum).src;
}
else {
var next = document.getElementById(nextElemId).src;
}
elem.src = next;
}
var images = document.getElementsByTagName('img');
for (var i = 0, len = images.length; i < len; i++) {
images[i].onclick = function() {
swapImageSrc(this,imgButton2);
};
}​
JS Fiddle demo.
Edited to add that, while it is possible to switch the src attribute of an image it seems needless, since both images are present in the DOM. The alternative approach is to simply hide the clicked image and show the next:
function swapImageSrc(elem, nextElemId) {
if (!elem) {
return false;
}
if (!nextElemId || !document.getElementById(nextElemId)) {
var id = elem.id.replace(/\d+/, ''),
nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
next = document.getElementById(id + nextNum);
}
else {
var next = document.getElementById(nextElemId);
}
if (!next){
return false;
}
elem.style.display = 'none';
next.style.display = 'inline-block';
}
var images = document.getElementsByTagName('img');
for (var i = 0, len = images.length; i < len; i++) {
images[i].onclick = function() {
swapImageSrc(this,imgButton2);
};
}​
JS Fiddle demo.
Edited to offer an alternate approach, which moves the next element to the same location as the clicked image element:
function swapImageSrc(elem, nextElemId) {
if (!elem) {
return false;
}
if (!nextElemId || !document.getElementById(nextElemId)) {
var id = elem.id.replace(/\d+/, ''),
nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
next = document.getElementById(id + nextNum);
}
else {
var next = document.getElementById(nextElemId);
}
if (!next){
return false;
}
elem.parentNode.insertBefore(next,elem.nextSibling);
elem.style.display = 'none';
next.style.display = 'inline-block';
}
var images = document.getElementsByTagName('img');
for (var i = 0, len = images.length; i < len; i++) {
images[i].onclick = function() {
swapImageSrc(this,imgButton2);
};
}​
JS Fiddle demo.

Categories

Resources