Show/Hide Multiple Div's - javascript

What is the best way to add another class to this script:
<script type="text/javascript">
$(document).ready(function(){
$('.carlocation').hide();
$('#parking-options').change(function() {
$('.carlocation').hide();
$('#' + $(this).val()).show();
});
});
</script>
I am fine with the same ID displaying this classes, I am just unsure about how to add another class to this script. As '.carlocation' , '.insertclass' or '.carlocation .insertclass' does nothing but break the script.
Thanks!
EDIT - The rest of the markup.
I would like .carlocation and .car-position to start off as two hidden divs but in the first drop down when "Self parking" is selected that the other two selections display.
<li>
<label for="select-choice-0" class="select">Parking Method:</label>
<select name="select-choice-15" id="parking-options" data-theme="b" data-overlay-theme="d" data-native-menu="false" tabindex="-1">
<option value="">Select One</option>
<option value="self">Self Parking</option>
<option value="auto">Valet Parking</option>
</select>
</li>
<li>
<div id="self" class="carlocation">
<h1>Enter Car Location:</h1>
<label for="select-choice-0" class="select">Floor:</label>
<select name="select-choice-15" id="location-floor" data-theme="b" data-overlay-theme="d" data-native-menu="false" tabindex="-1">
<option value="">Floor Select</option>
<option value="f1">F1</option>
<option value="f2">F2</option>
<option value="f3">F3</option>
<option value="f4">F4</option>
</select>
</div>
</li>
<li>
<div id="self" class="car-position">
<label for="select-choice-0" class="select">Row:</label>
<select name="select-choice-15" id="position-row" data-theme="b" data-overlay-theme="d" data-native-menu="false" tabindex="-1">
<option value="">Row Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
</select>
<li>

Hide your elements with CSS:
.carlocation, .car-position {
display: none;
}
Remove the repeated "self" id from both of the divs, and instead add the "self" value to the class attribute on both:
<li>
<div class="self carlocation">
<!-- ... -->
</div>
</li>
<li>
<div class="self car-position">
<!-- ... -->
</div>
</li>
Side Note: Your second div was missing its closing tag.
Then bind to the change event of the form:
$("#parking-options").on("change", function(){
$("div.self").toggle( $(this).val() === "self" );
});​​​​​​​​​​
This bases the visibility of all .self divs on the value of the select being "self". If "self" is selected, all div.self items will become visible. Otherwise, they become hidden.
Fiddle: http://jsfiddle.net/jonathansampson/5KJV5/
Or you could slide them into view:
$("#parking-options").on("change", function(){
$(this).val() === "self"
? $("div.self").slideDown()
: $("div.self").slideUp();
});​
Fiddle: http://jsfiddle.net/jonathansampson/5KJV5/2/

To select multiple selectors try this-
$("selector1,selector2")
It will definetly work.
For more information visit jQuery selectors reference.

Your jQuery selector can interact with multiple classes (or any other elements) by making a comma separated list within the quotes of the selector, in other words:
$('.carlocation, .insertclass, .anotherclass').hide();
Edit: Note that case sensitivity can be an issue in some cases, so '.insertclass' is not always the same as '.insertClass' - see JQuery class selectors like $(.someClass) are case sensitive? for more.
It looks like you might have gotten hung up initially by not having all of your selectors in the same quotes. Having a space between classes as in '.carlocation .insertclass' is actually saying "select an element with the class "insertclass" that is a child of an element with class "carlocation"
If you are going to be interacting with the same set of elements more than once, you can optimize your code by assinging them to a variable:
var $myselection = $('.carlocation, .insertclass, .anotherclass');
(note that putting the '$' in the variable name just helps remind you that it's a jQuery object, you could name it whatever you want).
You can now use any of the normal jQuery methods on $myselection:
$myselection.hide();
$myselection.show();
or use it later (so long as the variable is accessible within the scope that you're looking for it, which wouldn't be a problem in your initial example).

Related

Change selected element back to main base using Jquery

I am creating a select box that when I select a value in main select box Domains, it will appear other select box Types like Diatoms or Flagellates.... I am done with that part however, I am trying to change back the selected item in a select box that new appear to the main first one. I mean when I selected a Diatoms in Domains select box and it will appear then I select some item in Diatoms. Then I change other items in Domains and other select box will appear, the Diatoms will disappear. But the thing is the selected item that I select still remain like when I select it, I want to change it back to first option default, not the item. Here is my code
I already tried to put 'selectedIndex', 0. However it not work.
HTML
<ul class="inline_list">
<li class="Domains">
<select>
<option selected disabled hidden>Domains</option>
<option value="Diatoms">Diatoms</option>
<option value="Flagellates">Flagellates</option>
<option value="Dinoflagellates">Dinoflagellates</option>
<option value="Ciliates">Ciliates</option>
<option value="Coccolithophore">Coccolithophore</option>
<option value="Miscellaneous">Miscellaneous</option>
<option value="Other_plankton">Others</option>
</select>
</li>
<li class="Diatoms domains_types">
<select>
<option selected disabled hidden>Types</option>
<option value="Asterionellopsis">Asterionellopsis</option>
<option value="Bacillaria">Bacillaria</option>
</select>
</li>
<li class="Flagellates domains_types">
<select>
<option selected disabled hidden>Types</option>
<option value="amoeba">amoeba</option>
<option value="Chrysochromulina">Chrysochromulina</option>
</select>
</li>
<script src="js/select_box.js"></script>
</ul>
CSS
.domains_types{
display: none;
}
Jquery
$(document).ready(function(){
$('.Domains').ready(function(){
$('select').change(function(){
$("select option:selected").each(function(){
if($(this).attr("value")=="Diatoms"){
$('.domains_types').hide();
$('.Diatoms').css('display','inline-block');
}
if($(this).attr("value")=="Flagellates"){
$('.domains_types').hide();
$('.Flagellates').css('display','inline-block');
}
});
}).change();
});
});
You code can be easily optimised to reduce the redundancy in your code. Some straightforward improvements that we can do are:
Removing the ready event listener from $('.Domains'). The ready function is specific to the document object only, which maps to the DOMContentLoaded event. It's simply a convenience method made available by jQuery.
Instead of iterating through all options, you can simply get the value of the <select> element by calling this.value. This removes one layer of nesting form your code
Instead of creating a new if statement for each possible value, you can actually just use '.' + this.value to select the correct element, since you have one-to-one mapping of the first <select> elements options values to the <li> wrapper for the second level of <select> elements. For example, if the value selected is Flagellates, then the selector will select for $('.' + this.value) which evaluates to $('.Flagellates')
To "reset" your second level of <select> element, simply select the first option and set its selected property to true, i.e. $('option:first-child').prop('selected, true').
hidden is not an attribute/property of an <option> element. You can remove it.
With that in mind, here is the improved and working code:
$(document).ready(function() {
$('.Domains select').change(function() {
$('.domains_types')
.hide() // Hide the <li> element
.find('select option:first-child') // Get the nested select's first option
.prop('selected', true); // Select it
$('.' + this.value).css('display', 'inline-block');
}).change();
});
.domains_types {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="inline_list">
<li class="Domains">
<select>
<option selected disabled>Domains</option>
<option value="Diatoms">Diatoms</option>
<option value="Flagellates">Flagellates</option>
<option value="Dinoflagellates">Dinoflagellates</option>
<option value="Ciliates">Ciliates</option>
<option value="Coccolithophore">Coccolithophore</option>
<option value="Miscellaneous">Miscellaneous</option>
<option value="Other_plankton">Others</option>
</select>
</li>
<li class="Diatoms domains_types">
<select>
<option selected disabled>Types</option>
<option value="Asterionellopsis">Asterionellopsis</option>
<option value="Bacillaria">Bacillaria</option>
</select>
</li>
<li class="Flagellates domains_types">
<select>
<option selected disabled>Types</option>
<option value="amoeba">amoeba</option>
<option value="Chrysochromulina">Chrysochromulina</option>
</select>
</li>
</ul>

Multiple options from one drop down giving alternate results - Javascript/html

I'm looking to have separate sections of my form become visible dependant on the selection from a drop down menu.
Currently i'm having two issues, its only hiding the first area i want hidden and also i'm struggling with the syntax to get the multiple options working using if statements.
Am i looking at this the right way or is there an easier way of doing this.
In the code below i've only got 2 if statements as i've been struggling to get that correct so haven't done it for all 8 options i need to.
function showfield(name){
if (name=='Supplier meetings') {
document.getElementById('div1').style.display="block";
} else {
document.getElementById('div1').style.display="none";
if (name=='Product meetings') {
document.getElementById('div2').style.display="block";
} else {
document.getElementById('div2').style.display="none";
}
}
}
function hidefield() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
document.getElementById('div3').style.display='none';
document.getElementById('div4').style.display='none';
document.getElementById('div5').style.display='none';
document.getElementById('div6').style.display='none';
document.getElementById('div7').style.display='none';
document.getElementById('div8').style.display='none';
}
in my html i have:
<body onload="hidefield()">
<select name="acti" value="" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="1">Worked hours</option>
<option value="2">Overtime</option>
<option value="3">Sickness</option>
<option value="4">Unpaid leave</option>
<option value="5">Compassionate leave</option>
<option value="6">Holiday inc bank holidays</option>
<option value="7">Team meetings</option>
<option value="8">One to ones</option>
<option value="9">One to one prep</option>
<option value="10">Huddles</option>
<option value="Supplier meetings">Supplier meetings</option>
<option value="Product meetings">Product meetings</option>
<option value="Training/coaching">Training/coaching</option>
<option value="Handling other peoples cases">Handling other peoples cases</option>
<option value="15">Project work</option>
<option value="16">Surgery time for GK</option>
<option value="17">Letter checks and feedback</option>
<option value="18">MI/Reporting/RCA</option>
</select>
Then divs that contain the parts i need displayed off each option.
Hope that makes sense.
Thanks
Instead of writing condition for each option value, you can use the value directly in selecting the div that is to be shown:
function showfield(name){
hidefield();
document.getElementById( 'div-' + name).style.display="block";
}
For this to work, your id's should match up with corresponding option values.
e.g. <option value="1">1</option>
corresponding div:
<div id="div-1"></div>
You can add a data-div attribute to every option which will be ID of respective div which will be shown and other divs will be hidden.
You need a class on every div so they can be hidden using that class name except the div which will be shown based on selection.
HTML
<select name="acti" value="" onchange="showfield(this.options[this.selectedIndex].value)">
<option value="1" data-div="one">Worked hours</option>
<option value="2" data-div="two">Overtime</option>
</select>
<div id="one">First Div</div>
<div id="two">Second Div</div>
Javascript
function showfield(val)
{
var divID = $("select[name=acti]").find("option[value='" + val + "']").attr("data-div");
$(".divClass").hide();//You can also use hidefield() here to hide other divs.
$("#" + divID).show();
}

Handling Multiple ids in java script

Suppose I have following code:
<div class="topPagination">
<select id="itemsPage" onClick="changeItems(this.value);">
<option value="0">12 Items per Page</option>
<option value="100">View All</option>
</select>
</div>
<div id="mainContent">
</div>
<div class="bottomPagination">
<select id="itemsPage" onClick="changeItems(this.value);">
<option value="0">12 Items per Page</option>
<option value="100">View All</option>
</select>
</div>
<script>
function changeItems(itemsPage) {
want to get the id of the current <select> box.
}
</script>
how to get the id of the current box. like if select top select box or if i select bottom box.
Please help me to find a solution. I know with same ids is not the porper coding standard. But i have a situation like this.
This is not a valid HTLM code, all ids should be unique
But anyway you can use this code to get second checkbox
document.querySelectorAll('checkbox')[1];
if you need to browse through specific checkboxes, set them all some special class and use
document.querySelectorAll('.special_checkbox')[1];
If you "want to get the id of the current box", it will always be "itemsPage".
Having 2 objects in the DOM with the same ID is not valid HTML.
However, if you can change the DOM but can't change the IDs for some reason, you could do something like this:
<select id="itemsPage" onClick="changeItems(this);">
and then make your function:
function changeItems(select) {
// "select" is your element
// "select.value" is your value (that used to be passed in as "itemsPage"
}
Ultimately you should try and change one of the IDs, or use classes instead.
Try utilizing HTMLElement.dataset to substitute duplicate ids ; data-id="itemsPage-1" for first id=itemsPage ; data-id="itemsPage-2" for secondid=itemsPage ; pass selected element dataset.id at onClick event onClick="changeItems(this.value, this.dataset.id);"
function changeItems(itemsPage, id) {
console.log(itemsPage, id)
}
<div class="topPagination">
<select data-id="itemsPage-1" onClick="changeItems(this.value, this.dataset.id);">
<option value="0">12 Items per Page</option>
<option value="100">View All</option>
</select>
</div>
<div id="mainContent">
</div>
<div class="bottomPagination">
<select data-id="itemsPage-2" onClick="changeItems(this.value, this.dataset.id);">
<option value="0">12 Items per Page</option>
<option value="100">View All</option>
</select>
</div>
I think I know what it is you're trying to but this is a shot in the dark.
If you can change from using id to class this will work just fine.
window.onload=function(){
var PageItems=document.getElementsByClassName('itemsPage');
for(var i=0; i<PageItems.length; i++){
//Set Event Listeners for each element using itemsPage class name
PageItems[i].addEventListener('change',changeItems,false);
}
}
function changeItems(){
// New selected index
var Selected=this.selectedIndex;
var changeItems=document.getElementsByClassName('itemsPage');
for(var i=0; i<changeItems.length; i++){
//Change all select options to the new selected index.
changeItems[i].selectedIndex=Selected;
}
}
<div class="topPagination">
<select class="itemsPage">
<option value="0">12 Items per Page</option>
<option value="100">View All</option>
</select>
</div>
<div id="mainContent">
</div>
<div class="bottomPagination">
<select class="itemsPage">
<option value="07">12 Items per Page</option>
<option value="100">View All</option>
</select>
</div>
If you have any questions please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!

Show relevant divs when an html select option is clicked

I want a div to become visible when its corresponding select option is clicked (and to hide others) unfortunately my attempts at JavaScript are terrible.
CSS
#aaa, #bbb, #ccc {
display:none;
}
The HTML (I use the same id name for option and div - is this incorrect?)
<select>
<option>Select</option>
<option id="aaa" value="aaa" onclick="showExtra(this)">AAA</option>
<option id="bbb" value="bbb" onclick="showExtra(this)">BBB</option>
<option id="ccc" value="ccc" onclick="showExtra(this)">CCC</option>
</select>
<div id="aaa">
<p>AAA is aaamazing</p>
</div>
<div id="bbb">
<p>BBB is bbbriliant</p>
</div>
<div id="ccc">
<p>cccor blimey CCC</p>
</div>
The JavaScript
function showExtra(element)
{
I don't have clue .slideToggle("medium");
}
Get rid of the IDs in the <option> elements, they're not needed (or if they are, you need to rename them, e.g. optaaa, so they don't conflict with the IDs of the DIVs). Also, call the function from the dropdown's onchange event, not clicking on the options.
<select onchange="showExtra(this)">
<option>Select</option>
<option value="aaa">AAA</option>
<option value="bbb">BBB</option>
<option value="ccc">CCC</option>
</select>
Give all your DIVs a class, so you can operate on them as a group:
<div id="aaa" class="tab">
<p>AAA is aaamazing</p>
</div>
<div id="bbb" class="tab">
<p>BBB is bbbriliant</p>
</div>
<div id="ccc" class="tab">
<p>cccor blimey CCC</p>
</div>
In the JS, you can then operate on all the DIVs that do or don't match the value.
function showExtra(option) {
var divID = option.value;
$(".tab:not(#"+divID+")").slideUp();
$(".tab#"+divID).slideDown();
}
DEMO

Hiding a class of Div depending on Select statement option

I'm fairly new to javascript and I'm trying to make an form for my website and I'm stuck on the javascript,
This is what I have:
<script type="text/javascript">
function hide(opt) {
if (getElementsByClassName(opt).style.display='none';){
getElementsByClassName(opt).style.display='block';
}
else{
getElementsByClassName(opt).style.display='none';
}
}
</script>
What I intended the script to do was recieve a variable (the option chosen by the user) and then reveal all the elements with the class of the same name (so if the option was orc the orc div would be displayed, but be hidden if the option chosen was elf etc.)
Html:
<form name="chargen" action="" method="post">
Name:<Input name="name" type="text" />
Gender:<select name="gender">
<option>Choose Gender...</option>
<option>Male</option>
<option>Female</option>
</select>
Species:<select name="species" onchange="hide(document.chargen.species.options[
document.chargen.species.selectedIndex ].value)">
<option> Choose Species...</option>
<option value="human">Human</option>
<option value="orc">Orc</option>
<option value="elf">Elf</option>
<option value="dwarf">Dwarf</option>
<option value="drow">Drow</option>
<option value="ent">Ent</option>
</select>
<div class="human" style="display:none;">
Sub Species:<select name="subspecies1">
<option>Norseman</option>
<option>Hellenic</option>
<option>Heartlander</option>
</select>
</div>
<div class="orc" style="display:none;">
Sub Species:<select name="subspecies2">
<option>Black Orc</option>
<option>Fel Orc</option>
<option>Green Orc</option>
</select>
</div>
<div class="human" style="display:none;">
Homeland:<select name="homeland1">
<option>Choose Homeland...</option>
<option value="citadel">Citadel</option>
<option value="wildharn">Wildharn</option>
<option value="Merith">Merith</option>
</select>
</div>
<div class="orc" style="display:none;">
Homeland:<select name="homeland2">
<option>Choose Homeland...</option>
<option value="1">Berherak</option>
<option value="2">Vasberan</option>
</select>
</div>
Unfortunately nothing happens when I change the contents of the species combobox (I've tried on multiple browsers) What am I doing wrong?
I realise that getElementsByClassName() is a HTML5 function, but according to the interwebs it is compatible with all major browsers.
Thanks for your time
getElementsByClassName returns an array, you must iterate on the result. And be careful to the = in tests (instead of ==).
But I suggest you have a look at jquery. Your life will be easier as what you want can be done as :
$('.human, .orc, .elf, .dwarf, .drow, .ent').hide();
$('.'+opt).show();
(see fiddle : http://jsfiddle.net/dystroy/2GmZ3/)

Categories