I have two checkboxes. The checkBoxValidate function triggered by "onclick" assures that the two checkboxes cannot be both selected at the same time. The showMe function, also triggered by "onclick", displays a hidden div when check box is clicked. Everything just fine.
The problem:
When clicking on checkbox1 and then on checkbox2, the div triggered by checkbox1 is not automatically hidden. The idea is than when a checkbox is not selected the div triggered by it should not be visible... Please look at the demo.
Thank you!
DEMO:
http://jsbin.com/iNuPAREq/1/edit?html,js,output
HTML:
<form action="whatever" name="comanda11" method="post" onsubmit="return validate(this)">
<input type="checkbox" name="c1" onclick="showMe('content1'); checkBoxValidate(0);">
<input type="checkbox" name="c1" onclick=" showMe('content2'); checkBoxValidate(1);">
<div id="content1" style="display:none">
Content 1
</div>
<div id="content2" style="display:none">
Content 2
</div>
</form>
JS:
function showMe(box) {
var chboxs = document.getElementsByName("c1");
var vis = "none";
for (var i = 0; i < chboxs.length; i++) {
if (chboxs[i].checked) {
vis = "block";
break;
}
}
document.getElementById(box).style.display = vis;
}
function checkBoxValidate(cb) {
for (j = 0; j < 8; j++) {
if (eval("document.comanda11.c1[" + j + "].checked") == true) {
document.comanda11.c1[j].checked = false;
if (j == cb) {
document.comanda11.c1[j].checked = true;
}
}
}
}
change the markup to use radio buttons, and remove the inline javascript:
<form action="whatever" name="comanda11" method="post">
<input type="radio" name="c1" data-rel="content1" />
<input type="radio" name="c1" data-rel="content2" />
<div id="content1" style="display:none">Content 1</div>
<div id="content2" style="display:none">Content 2</div>
</form>
then do
var elems = document.getElementsByName('c1');
for (var i=elems.length; i--;) {
if (elems[i].addEventListener) {
elems[i].addEventListener ('change',fn,false);
}else if (elems[i].attachEvent) {
elems[i].attachEvent ('onchange',fn);
}
}
function fn() {
var rel = this.getAttribute('data-rel');
document.getElementById(rel=='content1'?'content2':'content1').style.display = 'none';
document.getElementById(rel).style.display = 'block';
}
FIDDLE
If you just have to use checkboxes, here's a working solution:
var elems = document.getElementsByName('c1');
for (var i=elems.length; i--;) {
if (elems[i].addEventListener) {
elems[i].addEventListener ('change',fn,false);
}else if (elems[i].attachEvent) {
elems[i].attachEvent ('onchange',fn);
}
}
function fn() {
var rel = this.getAttribute('data-rel');
for (var i=elems.length; i--;) {
if (elems[i] != this) elems[i].checked = false;
var id = elems[i].getAttribute('data-rel');
document.getElementById(id).style.display = elems[i].checked ? 'block' : 'none';
}
}
FIDDLE
Not an elegant solution but it works for your situation
function showMe (box) {
var chboxs = document.getElementsByName("c1");
var vis = "none";
document.getElementById("content1").style.display = "none";
document.getElementById("content2").style.display = "none";
for(var i=0;i<chboxs.length;i++)
{
if(chboxs[i].checked)
{
vis = "block";
break;
}
}
document.getElementById(box).style.display = vis;
}
The simplest way to get this to behave correctly is to set all divs to hidden before setting the div selected to block.
var divs = [document.getElementsByName("content1"),document.getElementsByName("content2")];
for(var i=0; i < divs.length; i++_ {
divs[i].style.display = 'none'
}
The above code should go above
document.getElementById(box).style.display = vis;
Note that There are much better ways to work with DOM elements. I would recommend looking into jQuery as a much simpler way of doing this. Also, manually building an array of two div elements is not the best way to do this, but I don't want to risk grabbing other divs that might be in your document.
In this situation, I set a global variable to the div being displayed at the time it is "unhidden". lets call it "lastdiv" as an example.
var lastdiv=false;
function showme(){
if(lastdiv){lastdiv.style.display='none';}
lastdiv=?????? // your code to find the div to unhide
lastdiv.style.display='block';
}
You have lots of other issues in your code to work out including the use of eval in a situation where it is clearly not warranted. There are better ways to do it without using eval.
Related
I'd like to show/hide multiple ID of elements.
I have a problem with the javascript in my HTML file.
Here's the javascript:
<Script type="text/javascript" language="JavaScript"><!--
function HideContent(d){
document.getElementById(d).style.display = "none";
}
function ShowContent(d){
document.getElementById(d).style.display = "block";
}
//--></script>
And my HTML:
<div class = "left" id="colsxmenu">
<ul>
<li> ENGLISH
<li>FRENCH
Actually, if I select ENGLISH it works good hiding the colsxmenu, but what I need is if I select FRENCH it should hide more than only 1 elements.
I tried to add ('colsxmenu';'colsxmenu2'), but that didn't works.
You can pass an array of elements to your function
<div id="first">first</div>
<div id="second">second</div>
ENGLISH
<script>
function HideContent(obj) {
for (var i = 0; i < obj.length; i++) {
document.getElementById([obj[i]]).style.display = 'none';
}
}
</script>
Define your HideContent function to accept variable number of argument. It should be some thing like below to hide multiple elements.
<script>
function HideContent() {
if (arguments.length > 0){
for(var i=0; i < arguments.length; i++{
document.getElementById(arguments[i]).style.display = "none";
}
}
}
</script>
After that you can call it like
HideContent('colsxmenu');
HideContent('colsxmenu', 'uniqename');
I'm trying to create a toggle button that can set the tags with class adsetTarget of HTML tags "li" to be hidden or visible on click event.
During page load, the state of "li" tags are hidden. This is the code that is setting the initial page load event to be hidden. This is working correctly.
var appBanners = document.getElementsByClassName('adsetTarget'), i;
for (var i = 0; i < appBanners.length; i ++) {
appBanners[i].style.display = 'none';
}
Below is the code that is trying to set toggle button functionality. On clicking first time, it is displaying the content, but on clicking it again, the content is not hiding, can someone help.
var adsetTargets = document.getElementsByClassName('adsetTarget'), i;
for (var i = 0; i < adsetTargets.length; i ++) {
if (adsetTargets[i].style.display = 'none')
adsetTargets[i].style.display = '';
else
adsetTargets[i].style.display = 'none'; //this is not working, I believe
}
You have to change the following line:
if (adsetTargets[i].style.display == 'none')
Notice the double equals?
You can use this to make it senstive to any styling you apply to your elements.
It will remember the elements previous style and re-apply it(in theory heh)
function showhide() {
var adsetTargets = document.getElementsByClassName('adsetTarget'), i;
for (var i = 0; i < adsetTargets.length; i ++) {
if (adsetTargets[i].style.display == 'none') {
adsetTargets[i].style.display = adsetTargets[i].getAttribute('data-previous');
}
else {
adsetTargets[i].setAttribute('data-previous',adsetTargets[i].style.display);
adsetTargets[i].style.display = 'none'; //this is not working, I believe
}
}
}
<ul>
<li class="adsetTarget" style="display:table">abc</li>
<li class="adsetTarget" style="display:block">123</li>
<li class="adsetTarget" style="display:inline-block">def</li>
<li class="adsetTarget" style="display:inline-block">456</li>
</ul>
<input type="button" onclick="showhide()" value="click me">
I try to hide some HTML elements onload and then show and manipulate them. The code works fine when I use element's individual IDs with getElementById() method. But when I try to do it more efficiently using the classes, it doesn't work. Here is the code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body onload="HideModals()">
<p id="p1" class="MyModal99">1. I will disappear or not.</p>
<p id="p2" class="MyModal99">2. I will disappear or not.</p>
<button id="toggle">Toggle</button>
<button id="hide">Hide</button>
<script>
$(document).ready(function(){
$("#toggle").click(function(){
$("#p1").toggle();
});
$("#hide").click(function(){
$("#p2").hide();
});
});
</script>
<script>
function HideModals() {
//document.getElementById("p1").style.display = 'none';
//document.getElementById("p2").style.display = 'none';
document.getElementsByClassName("MyModal99").style.display = 'none';
}
</script>
</body>
</html>
You cannot apply properties in bulk like that. This is why using jQuery is preferred for things like this:
$('.MyModal99').css('display', 'none');
If you want to do this without jQuery:
var nodes = document.getElementsByClassName("MyModal99");
for(var i = 0; i < nodes.length; i++) {
nodes[i].style.display = 'none';
}
It's because getElementsByClassName() returns an array-like object of elements. You need to access a specific element in order to change the style object.
You could iterate over the elements:
var elements = document.getElementsByClassName("MyModal99");
Array.prototype.forEach.call(elements, function (el) {
el.style.display = 'none';
});
or:
var elements = document.getElementsByClassName("MyModal99");
for (var i = 0; i < elements.length; i++) {
elements[i].style.display = 'none';
}
document.getElementsByClassName returns an array, which doesn't have a "style" property. You need to iterate over the array:
function HideModals() {
//document.getElementById("p1").style.display = 'none';
//document.getElementById("p2").style.display = 'none';
var modals = document.getElementsByClassName("MyModal99");
for (var i=0; i < modals.length; i++) {
modals[i].style.display = 'none';
}
}
The issue here is that document.getElementsByClassName("MyModal99") returns a list of items, so you'd have to loop through them and apply your properties one at a time. Something like this:
var elements = document.getElementsByClassName("MyModal99");
for ( var e in elements ) {
e.style.display = "none";
}
If you need to support older browsers, do it the old fashioned way without a for..in loop:
var elements = document.getElementsByClassName("MyModal99");
for ( var i = 0 ; i < elements.length ; ++i ) {
elements[i].style.display = "none";
}
Thats because document.getElementsByClassName returns an array of nodes. You need to iterate each of the returned nodes to set their styles individually.
var eleArray = document.getElementsByClassName('MyModal99');
for(var i = 0; i < eleArray.length; i++) {
eleArray[i].style.display = 'none';
}
You can use a for loop to cycle through all of the elements in the collection returned by getElementsByClassName like this:
var results = document.getElementsByClassName("MyModal99");
for (var i = 0; i < results.length; i++) {
results[i].style.display = 'none';
}
working demo: http://jsfiddle.net/gratiafide/3qg308bq/2/
I had difficulties with this code because I didn't know how to name jQuery functions. Now i know. Here is the corrected code:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js">
</script>
</head>
<body onload="HideModals()">
<p id="p1" class="MyModal99">1. I will disappear or not.</p>
<p id="p2" class="MyModal99">2. I will disappear or not.</p>
<button id="toggle">Toggle</button>
<button id="hide">Hide</button>
<script>
$(document).ready(function(){
$("#toggle").click(function(){
$("#p1").toggle(100);
});
$("#hide").click(function(){
$("#p2").hide(100);
});
});
function HideModals() {
$('.MyModal99').css('display', 'none');
}
</script>
Can someone show a way to show/hide a span using javascript
document.getElementById("test").style.display= 'visible';
document.getElementById("test").style.display= 'block';
In the HTML Code
<span id='test' ..
How can I overcome this problem. Is there any thing that I should think about?
UPDATE
I have a class like this one, I want to force mouse hovering on it.
<div id="test" class="tooltip effect">
<div id="second" href="#"> .. </div>
On css:
tooltip{..}
effect{..}
effect:hover{..}
Another option I tried besides your code is
document.getElementById("test").onmouseover = test.hover;
Should I re-write the hover class to another name-class, or should I tweak your code?
Use display none/default:
document.getElementById("test").style.display= 'none';
document.getElementById("test").style.display= '';
Below are some types and some easy to remember rules about them:
Default: the elements default property (generally block or inline)
Block: Generally on a line by itself. Has the width and height attributes (among other size/positioning attributes)
inline: on the same line as other elements/text. Does not have height/width attributes
Inherit: Inherits the parent element's display type
visible isn't a value for the display, you want none
I would do something like this to handle it:
function HideAndSeek(selector) {
var elements = undefined;
var displays = [];
if (!!selector.id) {
elements = [document.getElementById(selector.id)];
} else if (!!selector.class) {
elements = document.getElementsByClass(selector.class);
}
for (var elementIndex = 0; elementIndex < elements.length; elementIndex++) {
displays[elementIndex] = elements[elementIndex].style.display;
}
this.hide = function() {
for (var elementIndex = 0; elementIndex < elements.length; elementIndex++) {
elements[elementIndex].style.display = "none";
}
};
this.show = function() {
for (var elementIndex = 0; elementIndex < elements.length; elementIndex++) {
elements[elementIndex].style.display = displays[elementIndex];
}
};
}
This function can be used this way:
var hideAndSeek = new HideAndSeek({id: "test"});
and you can hide the element(s) by:
hideAndSeek.hide();
you can show them by:
hideAndSeek.show();
<span class="text-danger" id="spanAddressLine1" runat="server" style="display: none;"> //Here is your message </span>
JQuery code
For show:
$('#<%= spanAddressLine1.ClientID%>').show();
For hide:
$('#<%= spanAddressLine1.ClientID%>').hide();
Here spanAddressLine1 is the id of span
I currently have four divs, which are each linked to a hidden div:
div1 - div1hidden
div2 - div2hidden
div3 - div3hidden
div4 - div4hidden
When a user clicks on one of the divs the hidden div appears. When clicked on again the div disappears.
The problem I have is if all four divs are clicked on all four hidden will appear. What I would like to do is only show one at a time.
For Example if 'div1hidden' is showing and the user clicks on div2 before hiding div1hidden, div1hidden will hide and div2hidden will appear.
This is the code I have so far:
function hide_menu(id){document.getElementById(id).style.display = "none";}
function show_menu(id){document.getElementById(id).style.display = "block";}
<div class="div1" onclick="if (document.getElementById('div1hidden').style.display=='none') show_menu('div1hidden'); else hide_menu('div1hidden');"></div>
<div class="div2" onclick="if (document.getElementById('div2hidden').style.display=='none') show_menu('div2hidden'); else hide_menu('div2hidden');"></div>
<div class="div3" onclick="if (document.getElementById('div3hidden').style.display=='none') show_menu('div3hidden'); else hide_menu('div3hidden');"></div>
<div class="div4" onclick="if (document.getElementById('div4hidden').style.display=='none') show_menu('div4hidden'); else hide_menu('div4hidden');"></div>
Thanks in advance
Rick
Try something like this:
Add a function:
function hide_all() {
hide_menu('div1hidden');
hide_menu('div2hidden');
hide_menu('div3hidden');
hide_menu('div4hidden');
}
Now call that function before you show any hidden div:
<div class="div1" onclick="if (document.getElementById('div1hidden').style.display=='none') {hide_all(); show_menu('div1hidden'); } else { hide_menu('div1hidden'); }"></div>
I'm not sure what's wrong with just hiding all other divs before opening the one your need:
<div class="div1" onclick="if (document.getElementById('div1hidden').style.display=='none') { hide_menu('div2hidden'); hide_menu('div3hidden'); hide_menu('div4hidden'); show_menu('div1hidden');} else hide_menu('div1hidden');"></div>
<!-- and so on -->
I must say that this isn't exactly the best approach to do the comparison in the onclick - instead I suggest putting it inside the function, something like this:
<script type="text/javascript">
function flipDiv(id)
{
var vis = document.getElementById('div' + id + 'hidden').style.display;
if(vis == 'none')
{
document.getElementById('div1hidden').style.display = 'none';
document.getElementById('div2hidden').style.display = 'none';
document.getElementById('div3hidden').style.display = 'none';
document.getElementById('div4hidden').style.display = 'none';
document.getElementById('div' + id + 'hidden').style.display = 'block';
}
else
{
document.getElementById('div' + id + 'hidden').style.display = 'block';
}
}
</script>
...
<div class="div1" onclick="flipDiv(1)">...</div>
...
The easiest way will be to cache the current open menu.
<head>
<script type="text/javascript">
var current = null; //current is stored here
function hide_current(){
if(current !=null){
document.getElementById(current).style.display = "none";
}
}
function show_menu(id){
if(current == id){
hide_current(); //current is already open, close it
current = null; //reset current
} else {
document.getElementById(id).style.display = "block";
current = id;
}
}
</script>
</head>
<body>
<div class="div1" onclick="hide_current();show_menu('div1hidden');"></div>
<div class="div2" onclick="hide_current();show_menu('div2hidden');"></div>
<div class="div3" onclick="hide_current();show_menu('div3hidden');"></div>
<div class="div4" onclick="hide_current();show_menu('div4hidden');"></div>
</body>
Although the other suggested answers will accomplish what you want, none of them are very robust. This is based on the fact that your sample code is not very robust. It relies on inline javascript calls and hard coding to your elements.
Something like this will be easily extendable and less prone to breakage. Please note that some modifications will be necessary to accommodate old versions of IE (attachEvent support and getElementsByClassName support). But the concepts are the important thing.
Basically we get all the parent divs. Attach an event to their click. When they are clicked we hide all the divs that are supposed to be hidden and show the one we want.
http://jsfiddle.net/mrtsherman/8sgC2/2/
var divs = document.getElementsByClassName('menu');
for (var index = 0; index < divs.length; index++) {
divs[index].addEventListener('click', function() {
var contentDiv = null;
//hide all other divs
for (var i = 0; i < divs.length; i++) {
contentDiv = document.getElementById(divs[i].id + 'content');
contentDiv.style.display = 'none';
}
//show current item
contentDiv = document.getElementById(this.id + 'content');
contentDiv.style.display = 'block';
}, false)
}
<div class="menu" id="div1">one</div>
<div class="menu" id="div2">two</div>
<div class="menu" id="div3">three</div>
<div class="menu" id="div4">four</div>
<div class="content" id="div1content">one content</div>
<div class="content" id="div2content">two content</div>
<div class="content" id="div3content">three content</div>
<div class="content" id="div4content">four content</div>
Note that libaries like jQuery can do this in far less code, without having to account for browser differences and with cool effects like sliding or fading in.
http://jsfiddle.net/mrtsherman/8sgC2/3/
//bind to click event on the div
$('.menu').click( function() {
//get content div associated with the clicked div
var contentDiv = $(this).attr('id') + 'content';
//if no items are visible yet then show current
if ($('.content').filter(':visible').length == 0) {
$('#' + contentDiv).slideDown();
return;
}
//hide visible divs and show new div
$('.content').filter(':visible').slideUp('fast', function() {
$('#' + contentDiv).slideDown();
});
});
You can create the Display Div & Hidden div
at the same time and creating the click event in loop
This is source code which you can use to apply for unlimited divs
var n = 10;
var did = 'divDisplay';
var hid = 'divHidden';
function divDisplayOnclick()
{
for(var i=0; i<n; i++)
{
document.getElementById(did+i+hid).style.display = 'none';
}
document.getElementById(this.id+hid).style.display = 'block';
}
function createDivDisplay()
{
for(var i=0; i<n;i++)
{
var divDisplay = document.createElement('div');
divDisplay.id = did+i;
divDisplay.innerHTML = 'Click to display hidden div '+i;
divDisplay.className = did;
divDisplay.onclick = divDisplayOnclick;
document.body.appendChild(divDisplay);
var divHidden = document.createElement('div');
divHidden.id = did+i+hid;
divHidden.innerHTML = 'This is hidden div '+i;
divHidden.className = hid;
document.body.appendChild(divHidden);
}
}
createDivDisplay();
.divDisplay
{
border: 1px solid powderblue;
margin-bottom: 5px;
cursor: pointer;
}
.divHidden
{
border: 1px solid red;
margin-left: 20px;
margin-bottom: 10px;
display: none;
}