HTML5 Drop down with list - javascript

im currently working on bringing a website up to date. Iv taken the code from one of the old pages and put it in the new website. It works but dosnt do so when when its being validated by w3c.
When I try and validate the code I get this error : Attribute rel not allowed on element option at this point.
The new website is being done in HTML5.
Is their an alternative way of doing this with HTML5?
Iv included some images to show what supposed to happen and a link to a page with the original code .
This images shows the drop down box
This image shows the result of selecting somthing
The code can be seen here if you right click an view source : enter link description here

While the answer below was good , it didnt work in the end.
JS Fiddle here - JS FIDDLE DEMO
This code did however work:
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.3.js'></script>
<script type='text/javascript'>//<![CDATA[
$(window).load(function(){
var select = $( '#dropdown' );
function showTab( name ) {
name = '#' + name;
$( 'div' ).not( name ).hide();
$( name ).show();
}
select.change( function() {
showTab( $( this ).val() );
});
showTab( select.val() );
});//]]>
</script>
</head>
<body>
<form action="#">
<p>
<select id="dropdown" name="dropdown">
<option value="Pub-Chains" selected="selected"> Pub Chains </option>
<option value="Councils">Councils </option>
<option value="Property">Property </option>
<option value="Various">Various </option>
<option value="Universitys">Universitys </option>
</select>
</p>
</form>
<div id="Pub-Chains">
Pub-Chains
</div>
<div id="Councils">
Councils
</div>
<div id="Property">
Property
</div>
<div id="Various">
Various
</div>
</body>
</html>

First of all remember to include <!doctype html> in your file to set the browser to "html5 standards mode"
For the options tags you haw should use the value attribute. like
<option value="acc">Accountants</option>
In your javascript file you can access this attribute in the same way as you access the rel attribute.
For the divs / the targets you should use id or class (or title) since these are all global attributes that can be assagned to any object in html5 ref: http://www.w3schools.com/tags/ref_standardattributes.asp
Only use 'id' if the object is uniquely identified on your page, if you want to reference more object at a time consider using 'class'.
<div class="acc"> <!-- or 'div id="acc"' -->
<ul>
<li>Balmer Accountancy</li>
<li>BirchCooper</li>
<li>Tearle & Carver</li>
</ul>
</div>
Hope this helps :-)
EDIT: almost complete code:
JAVASCRIPT:
var containerTag = 'DIV';
var compatible = (
document.getElementById && document.getElementsByTagName && document.createElement
&&
!(navigator.userAgent.indexOf('MSIE 5') != -1 && navigator.userAgent.indexOf('Mac') != -1)
);
if (compatible)
{
//console.log('compatible');
document.write('<style>.accessibility{display: none}</style>');
var waitingRoom = document.createElement('div');
}
var hiddenFormFieldsPointers = new Object();
function prepareForm()
{
//console.log('prepareForm');
if (!compatible) return;
var marker = document.createElement(containerTag);
marker.style.display = 'none';
var x = document.getElementsByTagName('select');
for (var i=0;i<x.length;i++)
addEvent(x[i],'change',showHideFields)
var x = document.getElementsByTagName(containerTag); //divs
var hiddenFields = new Array;
for (var i=0;i<x.length;i++)
{
if (x[i].getAttribute('class')) //edit: class or id
{
var y = getAllFormFields(x[i]);
x[i].nestedRels = new Array();
for (var j=0;j<y.length;j++)
{
var rel = y[j].getAttribute('class'); //edit: class or id
if (!rel || rel == 'none') continue;
x[i].nestedRels.push(rel);
}
if (!x[i].nestedRels.length) x[i].nestedRels = null;
hiddenFields.push(x[i]);
}
}
while (hiddenFields.length)
{
var rel = hiddenFields[0].getAttribute('class'); //edit: class or id
if (!hiddenFormFieldsPointers[rel])
hiddenFormFieldsPointers[rel] = new Array();
var relIndex = hiddenFormFieldsPointers[rel].length;
hiddenFormFieldsPointers[rel][relIndex] = hiddenFields[0];
var newMarker = marker.cloneNode(true);
newMarker.id = rel + relIndex;
hiddenFields[0].parentNode.replaceChild(newMarker,hiddenFields[0]);
waitingRoom.appendChild(hiddenFields.shift());
}
setDefaults();
addEvent(document,'click',showHideFields);
}
function setDefaults()
{
//console.log('setDefaults');
var y = document.getElementsByTagName('input');
for (var i=0;i<y.length;i++)
{
if (y[i].checked && y[i].getAttribute('value')) //edit: value
intoMainForm(y[i].getAttribute('value')) //edit: value
}
var z = document.getElementsByTagName('select');
for (var i=0;i<z.length;i++)
{
if (z[i].options[z[i].selectedIndex].getAttribute('value')) //edit: value
intoMainForm(z[i].options[z[i].selectedIndex].getAttribute('value')) //edit: value
}
}
function showHideFields(e)
{
//console.log('showHideFields');
if (typeof e == "undefined")
e = window.event;
var tg = e.target || e.srcElement;
if (tg.nodeName == 'LABEL')
{
var relatedFieldName = tg.getAttribute('for') || tg.getAttribute('htmlFor');
tg = document.getElementById(relatedFieldName);
}
if (
!(tg.nodeName == 'SELECT' && e.type == 'change')
&&
!(tg.nodeName == 'INPUT' && tg.getAttribute('value')) //edit: value
) return;
var fieldsToBeInserted = tg.getAttribute('value'); //edit: value
if (tg.type == 'checkbox')
{
if (tg.checked)
intoMainForm(fieldsToBeInserted);
else
intoWaitingRoom(fieldsToBeInserted);
}
else if (tg.type == 'radio')
{
removeOthers(tg.form[tg.name],fieldsToBeInserted)
intoMainForm(fieldsToBeInserted);
}
else if (tg.type == 'select-one')
{
fieldsToBeInserted = tg.options[tg.selectedIndex].getAttribute('value'); //edit: value
removeOthers(tg.options,fieldsToBeInserted);
intoMainForm(fieldsToBeInserted);
}
}
function removeOthers(others,fieldsToBeInserted)
{
//console.log('removeOthers');
for (var i=0;i<others.length;i++)
{
var show = others[i].getAttribute('value'); //edit: value
if (show == fieldsToBeInserted) continue;
intoWaitingRoom(show);
}
}
function intoWaitingRoom(relation)
{
//console.log('intoWaitingRoom');
if (relation == 'none') return;
var Elements = hiddenFormFieldsPointers[relation];
for (var i=0;i<Elements.length;i++)
{
waitingRoom.appendChild(Elements[i]);
if (Elements[i].nestedRels)
for (var j=0;j<Elements[i].nestedRels.length;j++)
intoWaitingRoom(Elements[i].nestedRels[j]);
}
}
function intoMainForm(relation)
{
//console.log('intoMainForm');
if (relation == 'none') return;
var Elements = hiddenFormFieldsPointers[relation];
for (var i=0;i<Elements.length;i++)
{
var insertPoint = document.getElementById(relation+i);
insertPoint.parentNode.insertBefore(Elements[i],insertPoint);
if (Elements[i].nestedRels)
{
var fields = getAllFormFields(Elements[i]);
for (var j=0;j<fields.length;j++)
{
if (!fields[j].getAttribute('value')) continue; //edit: value
if (fields[j].checked || fields[j].selected)
intoMainForm(fields[j].getAttribute('value')); //edit: value
}
}
}
}
function getAllFormFields(node)
{
var allFormFields = new Array;
var x = node.getElementsByTagName('input');
for (var i=0;i<x.length;i++)
allFormFields.push(x[i]);
var y = node.getElementsByTagName('option');
for (var i=0;i<y.length;i++)
allFormFields.push(y[i]);
return allFormFields;
}
/** ULTRA-SIMPLE EVENT ADDING **/
function addEvent(obj,type,fn)
{
if (obj.addEventListener)
obj.addEventListener(type,fn,false);
else if (obj.attachEvent)
obj.attachEvent("on"+type,fn);
}
addEvent(window,"load",prepareForm);
/** PUSH AND SHIFT FOR IE5 **/
function Array_push() {
var A_p = 0
for (A_p = 0; A_p < arguments.length; A_p++) {
this[this.length] = arguments[A_p]
}
return this.length
}
if (typeof Array.prototype.push == "undefined") {
Array.prototype.push = Array_push
}
function Array_shift() {
var A_s = 0
var response = this[0]
for (A_s = 0; A_s < this.length-1; A_s++) {
this[A_s] = this[A_s + 1]
}
this.length--
return response
}
if (typeof Array.prototype.shift == "undefined") {
Array.prototype.shift = Array_shift
}
HTML (I HAD TO REMOVE SOME DIVS TO BE WITHIN stackoverflow.com POSTING LIMIT!!):
<!DOCTYPE html>
<title>Stackoverflow Code Sample</title>
<link type="text/css" rel="StyleSheet" href="./Stackoverflow_files/mk18.css">
<script type="text/javascript" src="./Stackoverflow_files/uf.js"></script>
</head>
<body class="twoColFixLtHdr">
<div id="container">
<div id="mainContent">
<h1 class="twoColFixLtHdr"><img width="480" height="29" src="http://mk18.comoj.com/Stackoverflow_files/weblinks.jpg" alt=""></h1>
<p></p>
<p>While advertising in MK18 we offer your company a free weblink. Select your choice by clicking the drop down and clicking the link to open.</p>
<form>
<select>
<option value="select">--- Click the drop down to select a weblink ---</option>
<option value="acc">Accountants</option>
<option value="acu">Acupuncture</option>
<option value="adv">Advertising</option>
<!-- //<option rel="aggt">Aggregates & Topsoil</option>// -->
<option value="ant">Antiques</option>
<option value="arcs">Architects & Surveyors</option>
<option value="artl">Artificial Lawns</option>
<!-- //<option rel="artf">Art & Framing</option>// -->
<option value="auc">Auctioneers</option>
<option value="auts">Automotive Services</option>
<option value="bat">Bathrooms</option>
<option value="bea">Beauticians</option>
<option value="boak">Boarding Kennels</option>
<option value="bui">Builders</option>
<option value="busn">Business Networking</option>
<!-- //<option rel="buso">Business Opportunities</option>// -->
<option value="but">Butchers</option>
<option value="carh">Car Hire</option>
<option value="carho">Care Home</option>
<option value="carj">Carpentry & Joiners</option>
<option value="carf">Carpets & Flooring</option>
<option value="cats">Catering Services</option>
<!-- //<option rel="cars">Car Sales</option>// -->
<option value="chas">Chauffeur Services</option>
<option value="chis">Chimney Sweep</option>
<option value="chir">Chiropractor</option>
<!-- //<option rel="choc">Chocolatier</option>// -->
<option value="cles">Cleaning Services</option>
<option value="clor">Clothing Repairs & Alterations</option>
<option value="coms">Computer Services</option>
<option value="corc">Corporate Clothing</option>
<!-- //<option rel="cou">Counselling</option>// -->
<option value="cra">Craftshop</option>
<option value="curb">Curtains & Blinds</option>
<option value="cycs">Cycle Sales & Repairs</option>
<option value="deli">Delicatessen</option>
<option value="denp">Dental Practice</option>
<option value="dogg">Dog Grooming</option>
<option value="dogt">Dog Trainer</option>
<option value="dogw">Dog Walking & Pet Sitting</option>
<option value="dcw">Doors, Conservatories & Windows</option>
<option value="edut">Education</option>
<!-- //<option rel="ele">Electricians</option>// -->
<option value="estl">Estate Agents</option>
<option value="eveh">Event Hire</option>
<option value="fars">Farm Shop</option>
<option value="fen">Fencing</option>
<option value="finm">Financial & Mortgage Services</option>
<option value="fooh">Foot Health</option>
<option value="fur">Furniture</option>
<option value="garn">Garden Nursery</option>
<!-- //<option rel="gars">Garden Sheds</option>// -->
<option value="gla">Glazier</option>
<option value="hai">Hairdresser</option>
<option value="heaf">Health & Fitness</option>
<!-- //<option rel="hola">Holiday Apartments</option>// -->
<option value="holh">Holistic Health</option>
<option value="hyp">Hypnotherapy</option>
<!-- //<option rel="inds">Independent Schools</option>// -->
<!-- //<option rel="iros">Ironing Services</option>// -->
<option value="kit">Kitchens</option>
<option value="lang">Landscaping & Gardening</option>
<!-- //<option rel="lawt">Lawn Treatment</option>// -->
<option value="lei">Leisure</option>
<option value="let">Letting Agencies</option>
<!-- //<option rel="lifc">Life Coach</option>// -->
<option value="loce">Local Events & Information</option>
<option value="marh">Marquee Hire</option>
<!-- //<option rel="nurs">Nursery Schools</option>// -->
<option value="off">Office Services</option>
<!-- //<option rel="oilt">Oil Tanks</option>// -->
<option value="opt">Opticians</option>
<option value="ost">Osteopath</option>
<option value="paid">Painting & Decorating</option>
<option value="pesc">Pest Control</option>
<option value="pluh">Plumbing & Heating</option>
<option value="prom">Property Maintenance</option>
<!-- //<option rel="pros">Property Surveyor</option>// -->
<option value="rec">Recruitment</option>
<!-- //<option rel="recs">Record Shop</option>// -->
<option value="res">Restaurants</option>
<option value="roos">Roofing Services</option>
<!-- //<option rel="salm">Sales & Marketing</option>// -->
<option value="sol">Solicitors</option>
<!-- //<option rel="sole">Solar Energy</option>// -->
<option value="sty">Stylist</option>
<!-- //<option rel="telb">Telephone & Broadband</option>// -->
<option value="tres">Tree Surgery</option>
<option value="tvsa">TV Services & Aerials</option>
<option value="tyrs">Tyre Services</option>
<!-- //<option rel="uph">Upholstery</option>// -->
<option value="vet">Vets</option>
<option value="vida">Video & Audio Services</option>
<option value="webd">Web Design</option>
<option value="wilw">Will Writer</option>
</select>
</form>
<div class="select">
</div>
<div class="acc">
<ul>
<li>Balmer Accountancy</li>
<li>BirchCooper</li>
<li>Tearle & Carver</li>
</ul>
</div>
<div class="acu">
<ul>
<li>Dr Joanne Sewell</li>
</ul>
</div>
<div class="adv">
<ul>
<li>Best of Buckingham</li>
<li>Essentially Local</li>
<li>Hogsty End</li>
<li>Roundabout Here</li>
</ul>
</div>
<div class="aggt">
<ul>
</ul>
</div>
<div class="ant">
<ul>
<li>Adstock Antiques</li>
</ul>
</div>
<div class="arcs">
<ul>
<li>Andrew Pegley</li>
<li>George Surveys Ltd</li>
</ul>
</div>
<div class="artf">
<ul>
<li>The Framing Centre</li>
</ul>
</div>
<div class="artl">
<ul>
<li>Prestige Lawns</li>
</ul>
</div>
<div class="auc">
<ul>
<li>Dickens Auctioneers</li>
</ul>
</div>
<div class="auts">
<ul>
<li>ChipsAway</li>
<li>Spot on Colours</li>
<li>Vass-Tech</li>
</ul>
</div>
<div class="bat">
<ul>
<li>Aspirational Interiors</li>
<li>Hatschek</li>
<li>Moreton Bathrooms</li>
</ul>
</div>
<div class="bea">
<ul>
<li>Harmony Beauty Therapy</li>
<li>Taylor Made Treatments</li>
<li>The Beauty Box</li>
<li>The Beauty Therapy Centre</li>
</ul>
</div>
<div class="boak">
<ul>
<li>Cayla Country Club</li>
</ul>
</div>
<div class="bui">
<ul>
<li>Country Renovations</li>
<li>Homefix</li>
</ul>
</div>
<div class="busn">
<ul>
<li>Bucks Fizz</li>
<li>The Athena Network</li>
</ul>
</div>
<div class="buso">
<ul>
</ul>
</div>
<div class="but">
<ul>
<li>Padbury Meats</li>
</ul>
</div>
<div class="carf">
<ul>
<li>ChemDry</li>
<li>M J Harris Flooring</li>
<li>Stainbusters</li>
</ul>
</div>
<div class="carh">
<ul>
<li>Two Hearts Wedding Car Hire</li>
</ul>
</div>
</div>
<!--end of list --> <br>
<div id="footer-spacer"></div>
<!-- end #mainContent -->
</div>
<!-- This clearing element should immediately follow the #mainContent div in order to force the #container div to contain all child floats --><br class="clearfloat">
<!-- end #footer -->
</body></html>
<!-- Hosting24 Analytics Code -->
<script type="text/javascript" src="http://stats.hosting24.com/count.php"></script>
<!-- End Of Analytics Code -->
There might be some errors so do tests!!
Good luck :-)
UPDATED::
Change your function prepareForm to somthing like this::
function prepareForm()
{
//console.log('prepareForm');
if (!compatible) return;
var marker = document.createElement(containerTag);
marker.style.display = 'none';
var x = document.getElementsByTagName('select');
for (var i=0;i<x.length;i++)
addEvent(x[i],'change',showHideFields)
var should_hide = new Array;
for (var i = 0; i < x.length; i++) {
for (var j = 0; j < x[i].length; j++) {
should_hide.push(x[i][j].getAttribute('value'));
}
}
var x = document.getElementsByTagName(containerTag); //divs
//console.log(should_hide);
var hiddenFields = new Array;
for (var i=0;i<x.length;i++)
{
var classname = x[i].getAttribute('class');
//if (x[i].getAttribute('class')) //edit: class or id
if (classname && should_hide.indexOf(classname) != -1)
{
var y = getAllFormFields(x[i]);
x[i].nestedRels = new Array();
for (var j=0;j<y.length;j++)
{
var rel = y[j].getAttribute('class'); //edit: class or id
if (!rel || rel == 'none') continue;
x[i].nestedRels.push(rel);
}
if (!x[i].nestedRels.length) x[i].nestedRels = null;
hiddenFields.push(x[i]);
}
}
while (hiddenFields.length)
{
var rel = hiddenFields[0].getAttribute('class'); //edit: class or id
if (!hiddenFormFieldsPointers[rel])
hiddenFormFieldsPointers[rel] = new Array();
var relIndex = hiddenFormFieldsPointers[rel].length;
hiddenFormFieldsPointers[rel][relIndex] = hiddenFields[0];
var newMarker = marker.cloneNode(true);
newMarker.id = rel + relIndex;
hiddenFields[0].parentNode.replaceChild(newMarker,hiddenFields[0]);
waitingRoom.appendChild(hiddenFields.shift());
}
setDefaults();
addEvent(document,'click',showHideFields);
}

Related

Selecting HTML select result in null, when reading the current option

I am trying to hide the elements with class furniture or book if DVD disc is selected. I want to do that dynamically, but in console, it shows, that it Cannot read property 'value' of null However, every option has a value, and that's strange. And of course, because of that, nothing is being changed
HTML select code:
<div class="iRow">
<div class="lclass"> <label for="typeselector">Product Category</label> </div>
<div class="tclass">
<select id="typeselector" name="productoptions">
<option value="DVD">DVD-Disc</option>
<option value="Book">Book</option>
<option value="Furniture">Furniture</option>
</select>
</div>
</div>
JS code:
<script>
var opt = document.getElementById("typeselector");
console.log(opt.value);
if(opt === "DVD-Disc")
{
console.log(document.getElementsByClassName("furniture"));
document.getElementsByClassName("furniture").style.display = "none";
document.getElementsByClassName("book").style.display = "none";
}
</script>
There are several issues:
getElementsByClassName returns a list, therefore, you loop over each element and hide it
There are no elements with such classes in the question
You should compare the value of the select
var opt = document.getElementById("typeselector");
if(opt.value === "DVD")
{
let furnitures = document.getElementsByClassName("furniture");
for(let i = 0; i < furnitures.length; i++)
furnitures[i].style.display = "none";
let books = document.getElementsByClassName("book");
for(let i = 0; i < books.length; i++)
books[i].style.display = "none";
}
<div class="iRow">
<div class="lclass">
<label for="typeselector">Product Category</label>
</div>
<div class="tclass">
<select id="typeselector" name="productoptions">
<option value="DVD">DVD-Disc</option>
<option value="Book">Book</option>
<option value="Furniture">Furniture</option>
</select>
</div>
</div>
<div class="book">Book 1</div>
<div class="book">Book 2</div>
<div class="furniture">furniture 1</div>
<div class="furniture">furniture 1</div>
The right way would be to set a listener on the select:
var opt = document.getElementById("typeselector");
opt.addEventListener("change", function(){
console.log(this.value)
if(this.value === "DVD"){
let furnitures = document.getElementsByClassName("furniture");
for(let i = 0; i < furnitures.length; i++)
furnitures[i].style.display = "none";
let books = document.getElementsByClassName("book");
for(let i = 0; i < books.length; i++)
books[i].style.display = "none";
}
});
<div class="iRow">
<div class="lclass">
<label for="typeselector">Product Category</label>
</div>
<div class="tclass">
<select id="typeselector" name="productoptions">
<option value="DVD">DVD-Disc</option>
<option class="book" value="Book">Book</option>
<option class="furniture" value="Furniture">Furniture</option>
</select>
</div>
</div>
The problem is here:
if(opt === "DVD-Disc")
You need to ask:
if(opt.Value === "DVD")
Also, when the page first loads, the DVD option is first, so it doesn't fire the on change event. If you select Book, then select DVD, the javascript below will fire in the working example:
<head>
<meta charset="utf-8" />
<title></title>
<script type="text/javascript">
function OnSelectionChange(select) {
var opt = document.getElementById("typeselector");
console.log(opt.value);
if (opt.value === "DVD") {
console.log("DVD Selected");
console.log(document.getElementsByClassName("furniture"));
document.getElementsByClassName("furniture").style.display = "none";
document.getElementsByClassName("book").style.display = "none";
}
}
</script>
</head>
<body>
<div class="iRow">
<div class="lclass"> <label for="typeselector">Product Category</label> </div>
<div class="tclass">
<select id="typeselector" name="productoptions" onchange="OnSelectionChange (this)">
<option value="DVD">DVD-Disc</option>
<option value="Book">Book</option>
<option value="Furniture">Furniture</option>
</select>
</div>
</div>
</body>
</html>

show/hide section in wordpress with select values

I use Divi Theme in Wordpress.
I have sections that I gave IDs.
I have a select, and for each option value I use the sections IDs.
I want show one section by changing the select option and hide the other section that is showed.
Here is the select :
<select name="years" id="mySelect" onchange="myFunction()">
<option value="">TOUTES LES ANNÉES </option>
<option value="section2020">2020</option>
<option value="section2019">2019</option>
<option value="section2018">2018</option>
<option value="section2017">2017</option>
<option value="section2016">2016</option>
<option value="section2015">2015</option>
</select>
Here is the javascript :
<script>
function myFunction() {
var x = document.getElementById("mySelect").value;
if (x.style === "display:none;") {
x.style = "display:block";
} else {
x.style = "display:none;";
}
}
</script>
Could you tell my why it's not working ?
thanks
Caroline
In your code, you are trying to style a string value x.style
If we see closely var x = document.getElementById("mySelect").value; this is returning a string value not an html element. But yes we can use this string value to get html element and make it visible and hide other.
function myFunction() {
var selectElement = document.getElementById("mySelect");
var selectedValue = selectElement.value;
var selectedElement = document.getElementById(selectedValue);
if (selectedElement.style.display === "none") {
var elements = document.getElementsByClassName('section');
for(var i = 0; i < elements.length; i++){
elements[i].style.display = "none";
}
selectedElement.style.display = "block";
}
else {
selectedElement.style.display = "none";
}
}
<select name="years" id="mySelect" onchange="myFunction()">
<option value="">TOUTES LES ANNÉES </option>
<option value="section2020">2020</option>
<option value="section2019">2019</option>
<option value="section2018">2018</option>
<option value="section2017">2017</option>
<option value="section2016">2016</option>
<option value="section2015">2015</option>
</select>
<div id="section2020" class='section' style='display:none'><h1>2020</h1></div>
<div id="section2019" class='section' style='display:none'><h1>2019</h1></div>
<div id="section2018" class='section' style='display:none'><h1>2018</h1></div>
<div id="section2017" class='section' style='display:none'><h1>2017</h1></div>
<div id="section2016" class='section' style='display:none'><h1>2016</h1></div>
<div id="section2015" class='section' style='display:none'><h1>2015</h1></div>
So thank you so much #Dupinder Singh. After playing with the code, I got it to work on my DIVI theme.
However, since you can't put in-line CSS styles on a Section in DIVI, I did the following. I went under each section and under the Advanced Tab -> Custom CSS -> Main Content = display: none;
Then since each section appeared like so I changed the javascript to the following:
<script>
function myFunction() {
var selectElement = document.getElementById("serviceoptions");
var selectedValue = selectElement.value;
var selectedElement = document.getElementById(selectedValue);
if (selectedElement.style.display === "") {
var elements = document.getElementsByClassName('section');
for(var i = 0; i < elements.length; i++){
elements[i].style.display = "";
}
selectedElement.style.display = "block";
}
else {
selectedElement.style.display = "none";
}
}
</script>
The following was my HTML for the Selection Menu:
<p style="text-align: center;">
<Select id="serviceoptions" onchange="myFunction()">
<option value="">Choose a Service</option>
<option value="behavior">Behavior Resources</option>
<option value="case">Case Management Resources</option>
<option value="education">Education Resources</option>
<option value="speceducation">Specialized Education Resources</option>
<option value="afterschool">After School Programs</option>
<option value="kidhealth">Children's Health Resources</option>
<option value="kidoralhealth">Children's Oral Health Resources</option>
<option value="homevisit">Home Visiting Resources</option>
<option value="nutrition">Nutrition Resources</option>
<option value="parent">Parent Resources</option>
<option value="transpo">Transportation Resources</option>
<option value="kidcare">Child Care Resources</option>
</select>
</p>
You can see it in action here: first1thousand.com/resources

problem related to filtering images with jquery

I am working on simple filtering images project with jquery I have a data-attribute called "data-genre" which contains multiple values
Ex: data-genre = "sci-fi, police, mystery, psychological"
when my data-genre has single value like data-genre = "action" am able to filter the images which contain action genre (through selecting action genre in select box)
but as you know an anime can have multiple genres so when I add multiple values like above example it shows nothing I want my jquery code in such a way that when I select police genre in select box it should loop through those multiple values of data-genre and display the images with police genre
This is my source code
HTML CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<title>Anime Filter</title>
<style>
*{
margin: 0 auto;
padding: 0 auto
box-sizing: border-box;
}
.an-filterbar{
text-align: center;
margin: 50px;
}
.ps-page{
margin: 100px;
}
.ps-page .ps-links{
margin-left: 30px;
float: left;
text-align: center;
}
</style>
</head>
<body>
<div class="an-filterbar">
<label for="an-search"><b>Type :</b></label>
<select class="type">
<option value="all">All</option>
<option value="tvseries">Tv series</option>
<option value="movie">Movie</option>
</select>
<br>
<label for="an-search"><b>Genre :</b></label>
<select class="genre">
<option value="all">All</option>
<option value="action">Action</option>
<option value="adventure">Adventure</option>
<option value="cars">Cars</option>
<option value="comedy">Comedy</option>
<option value="police">Police</option>
</select>
<br>
<label for="an-search"><b>Year :</b></label>
<select class="year">
<option value="all">All</option>
<option value="1990">1990</option>
<option value="1991">1991</option>
<option value="1992">1992</option>
<option value="1993">1993</option>
<option value="1994">1994</option>
</select>
<br>
<label for="an-search"><b>Season :</b></label>
<select class="season">
<option value="all">All</option>
<option value="winter">Winter</option>
<option value="spring">Spring</option>
<option value="summer">Summer</option>
<option value="fall">Fall</option>
</select>
<br>
<label for="an-search"><b>Status :</b></label>
<select class="status">
<option value="all">All</option>
<option value="airing">Airing</option>
<option value="finished">Finished</option>
<option value="notyetaired">Not yet Aired</option>
</select>
<br>
</div>
<div class="ps-page">
<div class="ps-links" data-type="movie" data-genre="adventure, comedy, action" data-year="1990" data-season="summer" data-status="notyetaired">
<a href="">
<figure>
<img src="assets/pimg-6.jpg" alt="Eizouken ni wa te wo dasu na">
<figcaption>
<b>Rating : N/R</b><br>
Eizouken ni wa te wo dasu na
</figcaption>
</figure>
</a>
</div>
<div class="ps-links" data-type="tvseries" data-genre="adventure, cars" data-year="1991" data-season="fall" data-status="airing">
<a href="">
<figure>
<img src="assets/pimg-7.jpg" alt="Somali to mori no kamisama">
<figcaption>
<b>Rating : N/R</b><br>
Somali to mori no kamisama
</figcaption>
</figure>
</a>
</div>
<div class="ps-links" data-type="tvseries" data-genre="action, comedy, cars" data-year="1992" data-season="summer" data-status="finished">
<a href="">
<figure>
<img src="assets/pimg-8.jpg" alt="Jibaku shounen hanako-kun">
<figcaption>
<b>Rating : N/R</b><br>
Jibaku shounen hanako-kun
</figcaption>
</figure>
</a>
</div>
<div class="ps-links" data-type="movie" data-genre="sci-fi, police, mystery, psychological" data-year="1993" data-season="spring" data-status="finished">
<a href="">
<figure>
<img src="assets/pimg-9.jpg" alt="Plunderer">
<figcaption>
<b>Rating : N/R</b><br>
Plunderer
</figcaption>
</figure>
</a>
</div>
</div>
<script>
$("select.type, select.genre, select.year, select.season, select.status").change(updateCategories);
function updateCategories() {
//get all the values
var caType = $('select.type').val();
var caGenre = $('select.genre').val();
var caYear = $('select.year').val();
var caSeason = $('select.season').val();
var caStatus = $('select.status').val();
$('.ps-page')
.find('.ps-links')
.hide()
.filter(function () {
var okcaType = true;
if(caType !== "all"){
okcaType = $(this).attr('data-type') === caType;
}
var okcaGenre = true;
if(caGenre !== "all"){
okcaGenre = $(this).attr('data-genre') === caGenre;
}
var okcaYear = true;
if(caYear !== "all"){
okcaYear = $(this).filter('data-year') === caYear;
}
var okcaSeason = true;
if(caSeason !== "all"){
okcaSeason = $(this).attr('data-season') === caSeason;
}
var okcaStatus = true;
if(caStatus !== "all"){
okcaStatus = $(this).attr('data-status') === caStatus;
}
//only fade a image if it satisfies all five conditions
return okcaType && okcaGenre && okcaYear && okcaSeason && okcaStatus;
}).fadeIn('fast');
}
</script>
</body>
</html>
try this code and select one of genre in select box it dosent display any images
I want solution in such a way that it should fit inside my code (without changing whole code) and explanation of how it works.
You need to split the data-genre attribute in to an array and check whether the selected Genre exist in that array.
if (caGenre !== "all") {
var genreArray = $(this).attr('data-genre').split(",").map(function (item) { return item.trim(); })
okcaGenre = genreArray.indexOf(caGenre) !== -1;
}
Here as you can see, I have splitted the data-genre string to an array and removed surrounding spaces of each item.
Updated code:
function updateCategories() {
//get all the values
var caType = $('select.type').val() || 'all';
var caGenre = $('select.genre').val() || 'all';
var caYear = $('select.year').val() || 'all';
var caSeason = $('select.season').val() || 'all';
var caStatus = $('select.status').val() || 'all';
$('.ps-page')
.find('.ps-links')
.hide()
.filter(function () {
var okcaType = true;
if (caType !== "all") {
okcaType = $(this).attr('data-type') === caType;
}
var okcaGenre = true;
if (caGenre !== "all") {
var genreArray = $(this).attr('data-genre').split(",").map(function (item) { return item.trim(); })
okcaGenre = genreArray.indexOf(caGenre) !== -1;
}
var okcaYear = true;
if (caYear !== "all") {
okcaYear = $(this).filter('data-year') === caYear;
}
var okcaSeason = true;
if (caSeason !== "all") {
okcaSeason = $(this).attr('data-season') === caSeason;
}
var okcaStatus = true;
if (caStatus !== "all") {
okcaStatus = $(this).attr('data-status') === caStatus;
}
//only fade a image if it satisfies all five conditions
return okcaType && okcaGenre && okcaYear && okcaSeason && okcaStatus;
}).fadeIn('fast');
}

How to submit after getting the value from select box option

I am a beginner with Javascript.
I have written code for getting the values from selected option and it works fine.
My question is after selecting all the three options, if I click on "submit"
button it should go to the next page.
can someone please help on this?
Condition to be executed while redirecting to another page:
if(strUser == 'AAA') && (strUser1 == 'DDD') && (strUser1 == 'GGG'))
{
window.location.replace("sample4.html");
}
else if(strUser == 'BBB') && (strUser1 == 'EEE') && (strUser1 == 'HHH'))
{
window.location.replace("sample5.html");
}
else
{
alert("please select all the 3 options");
}
}
Code:
<body
style="background-image: url(./img/ford3.png); background-size: cover;">
<h3>welcome user!!</h3>
<button class="ssystem">System</button>
<button class="sub">Sub-System</button>
<button class="subsub">Sub-Sub-System</button>
<div class="box">
<select name="select1" id="sys" onchange="showData();">
<option value="1">AAA</option>
<option value="2">BBB</option>
<option value="3">CCC</option>
</select>
</div>
<div class="box1">
<select id="sub" onchange="showData();">
<option value="4">DDD</option>
<option value="5">EEE</option>
<option value="6">FFF</option>
</select>
</div>
<div class="box2">
<select id="sub1" onchange="showData();">
<option value="7">GGG</option>
<option value="8">HHH</option>
<option value="9">III</option>
</select>
</div>
<input type="submit" value="Submit" id="button">
<script>
function showData() {
var e = document.getElementById("sys");
var e1 = document.getElementById("sub");
var e2 = document.getElementById("sub1");
var strUser = e.options[e.selectedIndex].text;
alert(strUser);
//var value = e1.options[e1.selectedIndex].value; //for index
//alert(value);
var strUser1 = e1.options[e1.selectedIndex].text;
alert(strUser1);
var strUser2 = e2.options[e2.selectedIndex].text;
alert(strUser2);
</script>
</body>
Solution
There were a few things wrong with your code.
Firstly, you want to make your state variables (values that can change) of a higher scope so you can share them between your functions. These are the values of your <select> html elements.
Since all your default values are at index zero, we can just default to that selected index value upon initialisation of the page.
We can extract the <select> DOM element into a variable with document.getElementById() and then get the selected option value out of it like so:
var strUser = document.getElementById("sys").options[0].text;.
Another thing is that your IF statements were incorrectly written. I amended this for example here:
if (strUser == 'AAA' && strUser1 == 'DDD' && strUser2 == 'GGG')
I left the alerts in there so you can see the sequential flow of the code.
Additionally, I moved the Javascript to a separate file and imported it through the <script> tag. This is a nice separation of concerns.
A link to a JSFiddle is here for a more visual effect of how the code works.
I hope this helps.
HTML
<body
style="background-image: url(./img/ford3.png); background-size: cover;">
<h3>welcome user!!</h3>
<button class="ssystem">System</button>
<button class="sub">Sub-System</button>
<button class="subsub">Sub-Sub-System</button>
<div class="box">
<select name="select1" id="sys" onchange="showData();">
<option value="1">AAA</option>
<option value="2">BBB</option>
<option value="3">CCC</option>
</select>
</div>
<div class="box1">
<select id="sub" onchange="showData();">
<option value="4">DDD</option>
<option value="5">EEE</option>
<option value="6">FFF</option>
</select>
</div>
<div class="box2">
<select id="sub1" onchange="showData()">
<option value="7">GGG</option>
<option value="8">HHH</option>
<option value="9">III</option>
</select>
</div>
<input type="submit" value="Submit" id="button" onclick="goToNextPage()">
<script src="./script.js"></script>
</body>
Javascript
var strUser = document.getElementById("sys").options[0].text;
var strUser1 = document.getElementById("sub").options[0].text;
var strUser2 = document.getElementById("sub1").options[0].text;
function showData() {
var e = document.getElementById("sys");
var e1 = document.getElementById("sub");
var e2 = document.getElementById("sub1");
strUser = e.options[e.selectedIndex].text;
alert(strUser);
strUser1 = e1.options[e1.selectedIndex].text;
alert(strUser1);
strUser2 = e2.options[e2.selectedIndex].text;
alert(strUser2);
}
function goToNextPage() {
if (strUser == 'AAA' && strUser1 == 'DDD' && strUser2 == 'GGG') {
window.location.replace("sample4.html");
}
else if (strUser == 'BBB' && strUser1 == 'EEE' && strUser2 == 'HHH') {
window.location.replace("sample5.html");
}
else {
alert("please select all the 3 options");
}
}

How to implement local storage on html?

(Updated)Here is the View Source.
For Example: You have a list of Names..I have to use a foreach loop because are over 100 names. And once the user selects the name, I have there phone number appears once you click on the button. I need the selected name to stay selected.
<!DOCTYPE html> <!--Required in every html-->
<html>
<head>
<!--Force browser to use latest version-->
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<!-- link allows use of .css and script allows use of javaScript -->
<!--<link rel="stylesheet" href="index.css"/>
<script src="init.js"></script>-->
<script>
function doFirst(){
}
</script>
</head>
<body>
<!--<button id='button'>Click me!</button>-->
<!-- -->
<h1> Friday 11-04-2016<br></h1>
<form action='index.php' method='post'>
Afternoon Shift Supervisor:
<select name="name"> <!-- COMBO Box PLUS onchange="submit();return false; makes data appear on selection, refreshs page"-->
<!-- AMOUNT(PROID), THEN FILL WITH THE CONTENT(PRONAME)-->
<option value="Declicious Apples!">Declicious Apples!</option>
<!-- AMOUNT(PROID), THEN FILL WITH THE CONTENT(PRONAME)-->
<option value="Comfy">Comfy</option>
<!-- AMOUNT(PROID), THEN FILL WITH THE CONTENT(PRONAME)-->
<option value="GREEN">GREEN</option>
</select>
<script>
var select = document.querySelector("name")[0];
var SelectOption = select.options[select.selectedIndex];
var lastSelected = localStorage.getItem('select');
if(lastSelected){
select.value = lastSelected;
}/*
select.onchange = function (){
lastSelected = select.options[select.selectedIndex].value;
console.log(lastSelected);
localStorage.setItem('select',lastSelected);
}
function updateSelection(which) {
if (typeof localStorage != "undefined")
localStorage.setItem("select", which.value);
}
window.onload = function () {
if (typeof localStorage != "undefined")
document.querySelector("#sel").value = localStorage["select"];
};*/
</script>
phone # : Comfy
<br> On Call Supervisor:
<select name="name2"> <!-- COMBO Box -->
<!-- AMOUNT(PROID IS VALUE..ASSOCIATIVE ARRAY), THEN FILL WITH THE CONTENT(PRONAME)-->
<option value="Declicious Apples!">Apples</option> <!-- ASSOCIATIVE ARRAY PRODDESC WILL BE OUTPUT-->
<!-- AMOUNT(PROID IS VALUE..ASSOCIATIVE ARRAY), THEN FILL WITH THE CONTENT(PRONAME)-->
<option value="Comfy">Jeans</option> <!-- ASSOCIATIVE ARRAY PRODDESC WILL BE OUTPUT-->
<!-- AMOUNT(PROID IS VALUE..ASSOCIATIVE ARRAY), THEN FILL WITH THE CONTENT(PRONAME)-->
<option value="GREEN">VEGGIES</option> <!-- ASSOCIATIVE ARRAY PRODDESC WILL BE OUTPUT-->
</select>
<!-- TESTING TO VERIFY I GET VALUE OF WHAT WAS SELECTED WORKS! -->
Phone #: Declicious Apples! <br><input type='submit' id='click me' value='Submit'><br/>
I have also tried(neither are saving the selected value when the page refreshes):
<script>
var select = document.querySelector("name");
var SelectOption = select.options[select.selectedIndex];
var lastSelected = localStorage.getItem('select');
if(lastSelected){
select.value = lastSelected;
}
select.onchange = function (){
lastSelected = select.options[select.selectedIndex].value;
console.log(lastSelected);
localStorage.setItem('select',lastSelected);
}
</script>
<form action='index.php' method='post'>
Afternoon Shift Supervisor:
<select name="name">
<?php foreach($data as $i=>$rows): ?>
<option value="<?=$rows['PRODDESC']?>"><?=$rows['PRODDESC']?></option>
<?php endforeach; ?>
</select>
<?php $name = $_POST["name"];?>
phone # : <?php echo $name; ?>
<br><input type='submit' name='click me' value='Submit'><br/>
</form>
Instead of doing it in the server side, use the client side to make it possible.
function updateSelection(which) {
if (typeof localStorage != "undefined")
localStorage.setItem("select", which.value);
}
window.onload = function () {
if (typeof localStorage != "undefined")
document.querySelector("#sel").value = localStorage["select"];
};
<select id="sel" onchange="updateSelection(this);">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
<option value="5">Option 5</option>
</select>
If the Stack Snippets are sandboxed, see the live preview at JSBin.

Categories