HTML Javascript toggle visibility of 'select' ie dropdown? - javascript

I've created a dropdown and label and surrounded them within a div, however, when i get the div in the following function, it doesnt hide/unhide the label and dropdown??
function ToggleDiv(DivID)
{
if (document.getElementById(DivID).style.display == "none")
{
document.getElementById(DivID).style.display = "block";
}
else
{
document.getElementById(DivID).style.display = "none";
}
}
i've set the default visibility to hidden in the css, as i want the elements to be hidden and then revealled when a checkbox is clicked. Is this the problem? Is the css always making the elements hidden??
#unis
{
visibility:hidden;
}
<div class='row'>
<label id='Recruitmentlbl' for='Recruitment'>Recruitment?:</label>
<input id='Recruitment' name='Recruitment' class='formcbx' type='checkbox' onclick=ToggleDiv("unis")<br />
</div>
<div class='row'>
<div id = "unis">
<label id='Universitylbl' for='University'>University institution:</label>
<select name="uni">
<option value="uni1">uni1</option>
<option value="uni2">uni2</option>
<option value="uni3">uni3</option>
<option value="uni4">uni4</option>
<option value="uni5">uni5</option>
</select><br />
</div>
</div>
but its not working?

The problem is that JS can't really read the style.display that's set in the CSS. So when you test against "none" the actual value that could be returned might be "none" or "" (no string at all.)
It's annoying, but test against the positive like this:
function ToggleDiv(DivID)
{
if (document.getElementById(DivID).style.display != "block")
{
document.getElementById(DivID).style.display = "block";
}
else
{
document.getElementById(DivID).style.display = "none";
}
}
Also, visibility and display are not the same thing. Visibility sets whether an object can be seen and display sets whether it has "layout". A div that has display:none; takes up no space on the page, but a div that has visibility:hidden; does. So even if the code does toggle the display value, you also need to toggle the visibility value too.

In case you want to save yourself from some typing (it's also faster):
function ToggleDiv(DivID) {
var style = document.getElementById(DivID).style;
style.display = (style.display != "none") ? "none" : "block";
}​
HTML
<p onclick="ToggleDiv('box')">toggle box</p>
<div id="box" style="display:none"></div>
About the visibility vs display issue. The difference is simple if you view it from the user's perspective.
display: none looks like the element has been removed
visibility:hidden looks like the element has been hidden
You can see a demo here: visibility vs display
The main point is that the two is not interchangeable: setting one won't affect the other.

Related

how can I alter my code to hide element on load?

I'm using this js code to show/hide elements on my site:
<script>
function myFunction3() {
var x = document.getElementById("dsec-three");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
Can anyone help me to set it so the elements are hidden on load and only show once activated?
you can use class for show/hide elements same as :
function showHide(){
element = document.getElementById('element1');
showHideEle(element)
}
function showHideMulti(){
elements = document.getElementsByClassName('multi');
Array.from(elements).forEach(ele => {
showHideEle(ele)
});
}
function showHideEle(ele){
let isHide = ele.classList.contains('hide');
if (isHide) {
ele.classList.remove("hide");
} else {
ele.classList.add("hide");
}
}
.hide {
display: none
}
<p class="hide" id="element1">para 1</p>
<button onclick="showHide()">Show/Hide</button>
<br />
<p class="hide multi">para 2</p>
<p class="hide multi">para 3</p>
<p class="hide multi">para 4</p>
<button onclick="showHideMulti()">Show/Hide Multi</button>
Your function myFunction3 already does the job of hiding and showing the relevant elements. All you need to do now is invoke the function when your document loads. You can do this by adding the following line inside your <script>:
document.addEventListener("load", myFunction3);
If you need the elements to stay hidden by default and show them after the document loads, you'll need to set the display property of those elements to none either via inline CSS.
Example (if your element is a div) :
<div id="dsec-three" style="display:none">
...
</div>
what do you mean by activated?
if you mean that after the load of your page, you would need an event listener.
follow these steps:
set the initial display of your element to none.
create an event listener like load: and add your function there:
document.addEventListerer('load', function(){
myFunction3();
})
the above code is telling the browser: 'when ever the page loads, call this function'

Javascript click on one element shows it, click on another: hide the first one and show the second

I am new here, I try to explain my problem as clear es possible.
I want to make working an index part of a big documentation. I have Buttons or Links (in this case in Example only divs) named from A to Z, and to every letter belongs a bunch of words starting with the chosen letter, like a dictionary.
What I want to achieve: if I click on a letter, the list of words will appear under the buttons. After that I click on another letter, the first activated list will disappear, and appear the next one, and so on.
I have found several explanation on different sites how to show and hide something, and it works already somehow (I must click on the letter again in order to hide it, so my goal was not reached yet), but I did not find a code or tutorial like this one.
Please help, may you have an idea!
My code:
html:
<div onclick="openIndexA()">A</div>
<div onclick="openIndexB()">B</div>
<div onclick="openIndexC()">C</div>
<!-- etc. -->
<div class="letters" id="A">
<p>A...1</p>
<p>A...2</p>
<p>A...3</p>
</div>
<div class="letters" id="B">
<p>B...1</p>
<p>B...2</p>
<p>B...3</p>
</div>
<div class="letters" id="C">
<p>C...1</p>
<p>C...2</p>
<p>C...3</p>
</div>
<!-- etc. -->
css:
.letters {
display: none;
}
in openIndex.js:
function openIndexA() {
var x = document.getElementById("A");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function openIndexB() {
var x = document.getElementById("B");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
function openIndexC() {
var x = document.getElementById("C");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
<!-- etc. -->
I know, that it is not the best and shortest way to do that, I could loop it through, I've tried it, but till now didn't achieve. I wanted to able to see first, how it works. But if you would have an advice for this, or the whole concept should be changed, please don't hesitate to explain, I am open to learn!.. :-)
See this fiddle!
var openIndex = document.querySelectorAll('.openindex');
var letters = document.querySelectorAll('.letters');
openIndex.forEach(function(el){
el.addEventListener('click', function(){
letters.forEach(function(e){
e.classList.remove('show');
});
var id = el.getAttribute('data-id');
document.getElementById(id).classList.add('show');
});
});
and add this css class
.show {
display: block;
}
Here is a solution and some advice:
function openIndex(id) {
document.querySelectorAll('.letters').forEach(elt => elt.classList.remove('active'));
document.querySelector('#'+id).classList.add('active');
}
.letters {
display: none;
}
.letters.active {
display: block;
}
<div onclick="openIndex('A')">A</div>
<div onclick="openIndex('B')">B</div>
<div onclick="openIndex('C')">C</div>
<!-- etc. -->
<div class="letters" id="A">
<p>A...1</p>
<p>A...2</p>
<p>A...3</p>
</div>
<div class="letters" id="B">
<p>B...1</p>
<p>B...2</p>
<p>B...3</p>
</div>
<div class="letters" id="C">
<p>C...1</p>
<p>C...2</p>
<p>C...3</p>
</div>
<!-- etc. -->
For your CSS: Don't work directly on the style, use classes as much as possible.
Here, as you can see, i've added a class active. If I add it, it will edit the style.
Then, for your JavaScript: if you copy paste more than two times, it's likely you could use a function.
Here, i've done the following: pass the ID you want to activate as a parameter.
Then, i take all the letters item and i remove the active class. Then, only for the one selected, i add the active class.
I hope this is clear and will help you :)

Check if a div is disabled jQuery

I need to check whether myDiv1 is disabled. If so, I need to hide myDiv2, otherwise I need to show myDiv2.
Here is what I have so far:
$(document).ready(function () {
var isDisabled = $('#myDiv1').is('[disabled=disabled]')
alert(isDisabled); //this always returns false
if(isDisabled)
$("#myDiv2").hide();
else
$("#myDiv2").show()
});
But isDisabled return always false even when myDiv1 is enabled. What am I missing here?
So many answers, but none addressing the actual problem: A div element doesn't allow an attribute of type disabled. On a div only global attributes are allowed, whereas disabled is allowed on form elements.
You can easily verify it by testing this HTML:
<div id="a" disabled></div>
<input id="b" disabled>
against this JavaScript:
var e = $('#a');
alert(e.is(':disabled'));
var e = $('#b');
alert(e.is(':disabled'));
Which will return false and true.
What's a solution then?
If you want to have an attribute that is actually named disabled use a data-* attribute:
<div id="c" data-disabled="true"></div>
And check it using this JavaScript:
var e = $('#c');
alert(e.data('disabled'));
or:
var e = $('#c');
alert('true' === e.attr('data-disabled'));
Depending on how you're going to handle attached data-*-attributes. Here you can read more about jQuery's .data() which is used in the first example.
Demo:
Try before buy
The reason why isDisabled returns false to you is, because you have most likely set the following in your HTML:
<div id = "myDiv1" disabled>...</div>
In reality, disabled means disabled = "", so, since "disabled" != "", if you keep using $('#myDiv1').is('[disabled=disabled]') you will always get false.
What will work:
To make this work, as other answers have mentioned, you can use:
$('#myDiv1').attr('disabled') == "disabled" (#guradio answer),
$('#myDiv1').is('[disabled=""]') or
$('#myDiv1')[0].getAttribute("disabled") != null.
What won't work:
While $('#myDiv1')[0].getAttribute("disabled") != null will work regardless of what element the attribute is set on, on the other hand, $('#myDiv1')[0].disabled will only work on 'form elements' and will return undefined for all others (check out the note at the end).
The same occurs when you use $('#myDiv1').is(':disabled') as well.
Alternatively, if you want to keep your code intact, you can set disabled = "disabled" in your HTML and the problem will be solved.
Working Example (using 2.):
/* --- JavaScript --- */
$(document).ready(function(isDisabled) {
isDisabled = $('#myDiv1').is('[disabled=""]');
if (isDisabled) $("#myDiv2").hide();
else $("#myDiv2").show()
/* Will return 'true', because disabled = "" according to the HTML. */
alert(isDisabled);
});
<!--- HTML --->
<script src = "//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "myDiv1" disabled>DIV 1</div>
<div id = "myDiv2">DIV 2</div>
Note: Beware, however, that the disabled attribute is meant to be used with 'form elements' rather than anything else, so be sure to check out the very informative answer of #insertusernamehere for more on this. Indicatively, the disabled attribute is meant to be used with the following elements:
button,
fieldset (not supported by IE),
input,
keygen (not supported by IE),
optgroup (supported by IE8+),
option (supported by IE8+),
select and
textarea.
$('#myDiv1').attr('disabled') == "disabled" ? $("#myDiv2").hide() : $("#myDiv2").show();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='myDiv1' disabled="true">1</div>
<div id='myDiv2'>2</div>
Try this way. But i dont think div has disable attribute or property
$('#myDiv1[disabled=true]').length > 0 ? $("#myDiv2").hide() : $("#myDiv2").show();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='myDiv1' disabled="true">1</div>
<div id='myDiv2'>2</div>
Using attribute selector
attribute selector
Description: Selects elements that have the specified attribute with a value exactly equal to a certain value.
First you need to set disabled property for your div
<div id="myDiv" disabled="disabled">This is Div</div>
Then you need to use this
$('#myDiv1').is('[disabled=disabled]')
Use this one:
$(document).ready(function () {
if($('#myDiv1').is(':disabled'))
$("#myDiv2").hide();
else
$("#myDiv2").show()
});
I hope this will help you:
$(document).ready(function () {
var isDisabled = $('#myDiv1').is(':disabled')
if(isDisabled)
$("#myDiv2").hide();
else
$("#myDiv2").show()
});
Use $("#div1").prop("disabled") to check whether the div is disabled or not. Here is a sample snippet to implement that.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<style>
.container {
width: 100px;
height: 100px;
background: grey;
margin: 5px;
float: left;
}
div {
width: 100%;
float: left;
}
</style>
</head>
<body>
<div>
<input type="checkbox" id="ChkBox" onclick="UpdaieDivStatus()" /> Toggle access
</div>
<div id="div1" class="container">Div 1</div>
<div id="div2" class="container">Div 2</div>
<script>
function UpdaieDivStatus() {
if ($("#ChkBox").prop('checked')) {
$("#div1").prop("disabled", true);
} else {
$("#div1").prop("disabled", false);
}
if ($('#div1').prop('disabled')) {
$("#div2").hide();
} else {
$("#div2").show();
}
console.log($("#div1").prop("disabled"));
}
</script>
</body>
</html>
If you look at this MDN HTML attribute reference, you will note that the disabled attribute should only be used on the following tags:
button, command, fieldset, input, keygen, optgroup, option, select,
textarea
You can choose to create your own HTML data-* attribute (or even drop the data-) and give it values that would denote the element being disabled or not. I would recommend differentiating the name slightly so we know its a custom created attribute.
How to use data attributes
For example:
$('#myDiv1').attr('data-disabled') == "disabled"
Why don't you use CSS?
html:
<div id="isMyDiv" disabled>This is Div</div>
css:
#isMyDiv {
/* your awesome styles */
}
#isMyDiv[disabled] {
display: none
}
Set the disabled attribute on any HtmlControl object. In your example it renders as:
<div id="myDiv1" disabled="disabled"><div>
<div id="myDiv2" ><div>
and in javascript can be checked like
('#myDiv2').attr('disabled') !== undefined
$(document).ready(function () {
if($('#myDiv1').attr('disabled') !== undefined)
$("#myDiv2").hide();
else
$("#myDiv2").show()
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<div id="myDiv1" disabled="disabled">Div1<div>
<div id="myDiv2" >Div1<div>

Why does this toggle function only work when the element is loaded a certain way?

I am trying to toggle some text, Q & A style with the question as a button that will display its answer when clicked. It functions fine when the CSS does not load the page with target element set to display:none
However, I want the element to be hidden by default until the button is clicked. For some reason, the js function does not work when the page is loaded in this manner. Anyone know why?
HTML
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="sample.css" media="screen" />
<script src="toggle.js" type="text/javascript"></script>
</head>
<body>
<button type="submit" class="question" id="q1" onclick="toggle_visibility('q1')">
This is my question?
</button>
<div class="dynamic-text-wrapper">
<div class="answer" id="a1">
Here is the answer to your question.
</div>
</div>
</body>
</html>
CSS
.dynamic-text-wrapper {height: 25px;}
.answer {
height: 25px;
display: none; /*DOESN'T WORK WHEN THIS LINE IS INCLUDED. But I want to not displayed to be default*/}
JavaScript
function toggle_visibility(questionID) {
var targetElement = document.getElementById('a'+parseInt(questionID.substring(1)));
if(targetElement.style.display == '') {
targetElement.style.display = 'none';
}
else {
targetElement.style.display = '';
}}
Instead of
targetElement.style.display = '';
you've got to write
targetElement.style.display = 'block';
In the 'if', you've got to check if you've established the display to block. If you haven't, the elment will be invisible (as set by the CSS rule):
if (targetElement.style.display == 'block') {
If you set display: none in CSS, doing .style.display = '' means that you're 'erasing' the inline value (which takes precedence over the value in a CSS file). So, by doing this, the new value for display will be 'none', as set in the CSS. By setting it to 'block', the final value of display is block.
I suggest you to read something about how CSS rules are applied.
Option 1
Use
.answer {
display: none; /* Hide by default */
}
and
targetElement.style.display = targetElement.style.display ? '' : 'block';
That is, if targetElement.style.display is falsy (you haven't set it, so it's hidden by default), you set it to 'block'. And if it is truthy (you have set it to 'block'), you clear it.
Option 2
This option will make your function reusable with non-block elements.
Use
<div class="answer default-hidden" id="a1"></div>
And, at onload, run
var els = document.getElementsByClassName('default-hidden');
for(var i=0, l=els.length; ++i) els[i].style.display = 'none';
And in your function:
targetElement.style.display = targetElement.style.display ? '' : 'none';

hide/show text area with textEditor depends on dropdown value

I use the NicEdit(www.nicedit.com) text-editor on my Text Area which is working and the below code to hide and show text area after selecting a value in the drop down it will show the text area but this is what i need help with;
1) i want the text area to show even before you select any value from the drop down.
2) i want the Text editor(NicEdit) to show on all the text area after selecting a value from the drop down to show the text area.
Js For Text-editor(Nicedit):
<script type="text/javascript" src="js/nicEdit.js"></script>
<script type="text/javascript">
bkLib.onDomLoaded(function() {
new nicEditor({maxHeight : 200}).panelInstance('area');
});
</script>
Js to hide and show text area:
<script type="text/javascript">
function showHide()
{
if(document.getElementById("color_dropdown").selectedIndex == 1)
{
document.getElementById("hidden1").style.display = ""; // This line makes the DIV visible
}
else {
document.getElementById("hidden1").style.display = "none"; // This line hides the DIV
}
if(document.getElementById("color_dropdown").selectedIndex == 2)
{
document.getElementById("hidden2").style.display = ""; // This line makes the DIV visible
}
else {
document.getElementById("hidden2").style.display = "none"; // This line hides the DIV
}
if(document.getElementById("color_dropdown").selectedIndex == 3)
{
document.getElementById("hidden3").style.display = ""; // This line makes the DIV visible
}
else {
document.getElementById("hidden3").style.display = "none"; // This line hides the DIV
}
}
</script>
Html drop down:
<select name="menu" id="color_dropdown" onchange="showHide()">
<option>Select Meun</option>
<option>One</option>
<option>Two</option>
<option>Three</option>
</select>
<textarea id="hidden1" name="area" display:none;" id="area">ggggggggggggggggg</textarea>
<textarea id="hidden2" name="area" display:none;" id="area">hhhhhhhhhhhhhhhhh</textarea>
<textarea id="hidden3" name="area" display:none;" id="area">yyyyyyyyyyyyyyyyy</textarea>
Just a small note, you have more have multiple id attributes per text area and the second id's have the same value, this should be a class. The "display:none;" in your textareas are not in style tags(style="display:none;"), also try linking/loading the javascript at the bottom of the html page just before the the last html tag(or last body tag).
I am not sure if this will fix your problem, but these could be issues.

Categories