Javascript show/hide multiple DIV's - javascript

I'm in need of a bit of help. I have a current script that switches div's between being visible and hidden depending on a dropdown selector, it works as it was originally designed absolutely fine.
The problem i have is that i need to modify it to change more than 1 div on the page. Currently i'm using the same ID for the div's but only the first item on the page is updated. Reading over the JS this makes sense, but i can't figure out how to modify it to get the desired result?
Javascript:
var lastDiv = "";
var lastProd = "";
function showDiv(divName, productID) {
if (productID == lastProd) {
$("#"+lastDiv).hide();
$("#"+divName).fadeIn(".visible-div-"+productID);
}
else {
$(".visible-div-"+productID).hide();
$("#"+divName).fadeIn(".visible-div-"+productID);
}
lastProd = productID;
lastDiv = divName;
}
The selector:
<select onchange="showDiv('pxo_'+this.value,2);" name="pre_xo_id">
<option value="3">Blue - £120.00</option>
<option value="4">Red - £120.00</option>
<option value="5">Yellow - £120.00</option>
The DIV's:
<div id="pxo_3" class="visible-div-2" style="display: none;">RED</div>
<div id="pxo_4" class="hidden-div visible-div-2" style="display: none;">BLUE</div>
<div id="pxo_5" class="hidden-div visible-div-2" style="display: block;">YELLOW</div>
<div id="pxo_3" class="visible-div-2" style="display: none;">1 In Stock</div>
<div id="pxo_4" class="hidden-div visible-div-2" style="display: none;">1 In Stock</div>
<div id="pxo_5" class="hidden-div visible-div-2" style="display: none;">0 In Stock</div>

id's must be unique, that's why only the first item is being update. You may put those values to class instead to allow multiple selection.

First you can not use one id for morethan one element.They must be unique.Apply same css class to those elements.
We can use same class instead to allow multiple selection.

IDs are supposed to be used for only a single element on the page. You want to use css selectors.

Thank you for the help all, I have modified the JS to look for both ID and Class as i am unable to change part of the code due to it being protected by ioncube.
This seems to have the desired result:
var lastDiv = "";
var lastProd = "";
function showDiv(divName, productID) {
if (productID == lastProd) {
$("#"+lastDiv).hide();
$("#"+divName).fadeIn(".visible-div-"+productID);
$("."+lastDiv).hide();
$("."+divName).fadeIn(".visible-div-"+productID);
} else {
$(".visible-div-"+productID).hide();
$("#"+divName).fadeIn(".visible-div-"+productID);
$(".visible-div-"+productID).hide();
$("."+divName).fadeIn(".visible-div-"+productID);
}
lastProd = productID;
lastDiv = divName;
}

Related

How to display just one element with same id

This is my first question at stack overflow
i just wanted to know a simple solution for the following case
<div *ngFor="let d of w.event">
<div class="date" id="d.date" >
<p>
<span style="font-size:1.75em">{{d.date | date:'dd'}}</span>
<br>
<strong> {{d.date | date:'EEE'}}</strong>
</p>
</div>
the looped div can have the same id
I just want to display the first div with a particular date and ignore the rest
can this be achieved with CSS or JavaScript
You can't use the same id on two elements. It's one of the few restrictions on ids.
You can use a class:
<div class="show">Yes</div> <div class="show">No</div>
...and then show either the first or second by using index 0 or index 1 after getting a list of matching elements:
var list = document.querySelectorAll(".show");
list[0].style.display = "none"; // Hides the first one
// or
list[1].style.display = "none"; // Hides the second one
Some other thoughts:
1. Rather than using style.display as I did above, you might add a class that hides the element.
2. You might use separate ids (or classes) for the elements so you don't need to index, e.g.:
<div id="show-yes">Yes</div> <div id="show-no">No</div>
then
document.getElementById("show-yes").style.display = "none";
// or
document.getElementById("show-no").style.display = "none";
On all browsers in my experience, you can do the first thing above (with querySelectorAll) with your invalid HTML with a selector like "[id=show], but don't. Fix the HTML instead.
In your question update, you show:
<div *ngFor="let d of w.event">
<div class="date" id="d.date" >
...
You've said you're aware of the fact you can't have multiple elements with the same id, so why code that? You can easily give them unique ids:
<div *ngFor="let d of w.event; let i = index">
<div class="date" id="d.date{{i}}" >
...
First of all, in HTML ID is a unique selector so one ID can be associate with only one element. if you want to achieve your desired functionality you have to assign different id for both DIV. and use javascript to hide and show DIV
<div id="showYes">Yes</div> <div id="showNo">No</div>
If you want to show one at a time you can go with *ngIf , as it will show only one at a time
<div id="show" *ngIf='your_status'>Yes</div>
<div id="show" *ngIf='!your_status'>No</div>
After your question update , you can create custom filter that will only return unique date , so only first unique date will be shown
// CREATE A PIPE FILTER :
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({name: 'checkUniqueDate'})
export class UniqueDatePipe implements PipeTransform {
transform(dataArray) {
let dates = [];
return dataArray.filter(data => {
return if(dates.indexOf(data.date) === -1) {
dates.push(data.date);
return true;
} else {
return false;
}
});
}
}
// TEMPLATE SIDE :
<div *ngFor="let d of (w.event | checkUniqueDate )">
Add the date in class also, then you can try below code
.YOUR_DATE{
display:none
}
.YOUR_DATE:first-child{
displany:inline
}

Dynamically change img ng-repeat using firebase

I have a page where a teacher can select a class (of school students). Then the teacher can create groups of students from this class by dragging avatars of the students.
I have a drop down list of classes and a div filled with avatars of the students.
The HTML:
<select name="chosenClass" onchange="chooseClass(this.value)">
<option ng-repeat="(key, value) in techerClasses">{{key}}</option>
</select>
...
<div id="div0" ondrop="drop(event)" ondragover="allowDrop(event)" class="groupDiv">
<img ng-repeat="(key, value) in classStudents" id={{key}} src="http://placehold.it/30x30/{{value}}" draggable="true" ondragstart="drag(event)">
</div>
The controller code:
chooseClass = function (classInfo) {
if (classInfo > 0){
$rootScope.classesRef.child(classInfo).on('value', function (dataSnapshot){
$rootScope.classStudents = dataSnapshot.val().members;
});
}
}
If I add data manually to the $rootScope.classStudents before
the page loads the avatars will show correctly.
console.log($rootScope.classStudents) after
$rootScope.classStudents = dataSnapshot.val().members; confirms
that the right data is in there.
But the avatars are not showing.
If I click "back" in the browser and then "forward" - the avatars
will show. This leads me to think that I need something that will
tell the <img ng-repeat... to refresh?
You're missing a $rootScope.$apply as you've done something outside of angular:
chooseClass = function (classInfo) {
if (classInfo > 0){
$rootScope.classesRef.child(classInfo).on('value', function (dataSnapshot){
$rootScope.classStudents = dataSnapshot.val().members;
$rootScope.$apply();
});
}
}
Alternatively look into using $firebaseArray:
chooseClass = function (classInfo) {
if (classInfo > 0){
$rootScope.classStudents = $firebaseArray($rootScope.classesRef.child(classInfo).child('members'))
}
}
set src="http://placehold.it/30x30/{{value}}" to ng-src="http://placehold.it/30x30/{{value}}" to add the src attribute to the digest.
Also $rootScope.$apply or $timeout(angular.noop) if you need a "save digest"

Replacing divs that can be replaced in html/javascript

Hi i'm trying to replace some divs with other divs, this works fine but when i try to replace the second load of divs they don't change anymore.
Basicaly I'm trying to create a "winetour" that lets a user choose some options and generates the perfect wine to go along with it.
You get presented with a couple of options (img links) and if you click one the div's content changes and presents another set of clickable images taking you deeper in your process of choosing a great wine.
HTML:
<div id"Gelegenheid">
<img src="Images/Ontbijt.jpg" id="ontbijt" alt="Ontbijt">
<img src="Images/Borrel.jpg" id="borrel" alt="Borrel">
<img src="Images/Dinner.jpg" id="feest" alt="Diner">
<img src="Images/Feest.jpg" id="diner" alt="Feest">
</div>
<div id"Ontbijt" style="display: none"> Some content that shows trough the "tour"</div>
<div id"Borrel" style="display: none"> Some content that shows trough the "tour"</div>
<div id"Dinner" style="display: none">
<img src="Images/White.jpeg" id="ontbijt-licht" alt="ontbijt-licht">
</div>
<div id"Dinner-detail-voor" style="display: none"> Some content that shows trough the "tour"</div>
<div id"Dinner-detail-head" style="display: none"> Some content that shows trough the "tour"</div>
JavaScript:
function continueTour(i) {
if (i==1) {
document.getElementById("Gelegenheid").innerHTML = document.getElementById("Ontbijt").innerHTML;
} else if (i==2) {
document.getElementById("Gelegenheid").innerHTML = document.getElementById("Borrel").innerHTML;
} else if (i==3) {
document.getElementById("Gelegenheid").innerHTML = document.getElementById("Diner").innerHTML;
} else if (i==4) {
document.getElementById("Gelegenheid").innerHTML = document.getElementById("Feest").innerHTML;
} else {
document.getElementById("Dinner").innerHTML = document.getElementById("Dinner-detail-voor").innerHTML;
}
}
So basically if you click on a link that's inside the "Gelegenheid" div you will be taken to for example Dinner, but the problem is, inside dinner there are some more links and i want to link them for example to "Dinner-detail-voor"
I want to make this working with core JavaScript (so no JQuery) but i don't know what's going on?
Thanks in advance!
Found the answer.
Added
document.getElementById("from").style.display = "none" ;
document.getElementById("to").style.display = "table" ;
to each of the javscript index functions, now it works where 'from' is the father and 'to' is the child that is being linked to, not very neat but it works,
If someone has a shorter or alternative solution feel free to post!
first we create an array for all the content, array is base 0 so we start from function myFunction(0); next we create a tag with updated variable in them. the if statement is use to reset the variable when hit max. hope this help.
http://jsfiddle.net/xgay3f83/3/
function continueTour(i) {
var content = ['content 1', 'content 2', 'content 3', 'content 4'];
var target = document.getElementById('target');
var next = i + 1;
var end = content.length;
if(next>end) {
i = 0;
next = 1;
}
var openTag = '<a href="#" class="hvr-grow" onClick = "continueTour('+next+')">';
var closeTag = '</a>';
target.innerHTML = openTag+content[i]+closeTag;
}

Get next textarea outside div without id

I need to get the next textarea, but I'm not being able with next or even find.
Sample code HTML:
<div>
<div class="guides_chapters_button" onclick="surroundtest('[center]', '[/center]');">Center</div>
<div class="guides_chapters_button" style="text-decoration: underline;" onclick="surround('[u]', '[/u]');">u</div>
</div>
<textarea class="guides_chapters_textarea" id="textareamatch" name="matchupm" rows="7" cols="25"></textarea>
JS:
window.surround = function surround(text2,text3){
$("#textareamatch").surroundSelectedText(text2, text3);
}
function surroundtest(text2,text3){
var c = $(this).parent().next('textarea');
c.surroundSelectedText(text2, text3);
}
JS FIDDLE: http://jsfiddle.net/qmpY8/1/
What I need working is surroundtest, the other is an example working but using the id. I would love to replace that one because Im usinc cloned objects.
The this statement in surroundtest applies to the window object and not the element. What you should do is to change the function definition as so:
function surroundtest(element, text2,text3){
var c = $(element).parent().next('textarea');
...
}
And the HTML accordingly:
<div class="guides_chapters_button" onclick="surroundtest(this, '[center]', '[/center]');">Center</div>
If this is the HTML you are going with, then .closest() can also be used to get the textarea element.Like below:
var c = $(element).parent().closest('textarea');

Javascript onclick change variable value

I am new to JavaScript and I need some help. I am making a website and I have several images of team members that if clicked (so I'm guessing the onclick event) will change the variable values corresponding to that team member. For instance, if I click on a picture of Bill Gates, in a separate div, I need to have a variable (let's say Name) change value to Bill Gates. Then, if I click on an image of Steve Jobs, the variables containing Bill Gates' data will get overwritten with the data of Steve Jobs. How do I do this?
Assuming mark-up like the following:
<div id="gallery">
<img class="people" data-subject="Steve Jobs" src="path/to/imageOfSteve.png" />
<img class="people" data-subject="Bill Gates" src="path/to/imageOfBill.png" />
</div>
<span id="caption"></span>
Then a relatively simple, and plain JavaScript, approach:
function identifySubject(image, targetEl) {
if (!image) {
return false;
}
else {
var targetNode = document.getElementById(targetEl) || document.getElementById('caption'),
person = image.getAttribute('data-subject');
text = document.createTextNode(person);
if (targetNode.firstChild.nodeType == 3) {
targetNode.firstChild.nodeValue = person;
}
else {
targetNode.appendChild(text);
}
}
}
var images = document.getElementsByClassName('people');
for (var i=0, len=images.length; i<len; i++) {
images[i].onclick = function(e){
identifySubject(this, 'caption');
};
}
JS Fiddle demo.
Onclick attribute is right. You need to add the name of a javascript function to the image's onclick attribute (eg <img src="" onclick="changeVariable()"...).
If you want text on the page to change depending on who you click on, you'll need to look at selecting divs in Javascript using getElementById() or similar and look at the InnerHTML property.
See: http://woork.blogspot.co.uk/2007/10/how-to-change-text-using-javascript.html
Hope this helps
<img src="path/to/image1" onclick="getValue('bill gates')" />
<img src="path/to/image2" onclick="getValue('steve jobs')"/>
<div id="show_value"></div>
<script>
function getValue(val){
document.getElementById('show_value').innerHTML = val
}
</script>
HTML:
<div class="member"><img src="billgates.jpg" /><span>Bill Gates bla bla</span></div>
<div class="member"><img src="stevejobs.jpg" /><span>Steve Jobs bla bla</span></div>
<div id="variables"></div>
JS:
$(function(){
$('.member img').click(function(){
$('#variables').html($(this).closest('span').html());
});
});

Categories