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

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>

Related

Document.write method

So, I'm trying to make a JS action where it should display the selected items from the list, I can only select one but I want to select more than one and view it in a list
<body>
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
<script>
var output = '';
let issues = document.getElementById("issue");
for (i = 0; i < issues.length; i++) {
output += document.write("<li>" + issues[i].text + </li>").innerHTML = issues;
}
</script>
</ul>
</body>
You need to use an event listener to listen for a change of selection and you need to update the html of the element. You rarely ever want to use document.write in an application.
const issueSelect = document.getElementById("issue");
// listen for a change
issueSelect.addEventListener("change", selChanged);
function selChanged() {
var output = '';
let issues = issueSelect.options;
// loop over the options
for (var i = 0; i < issues.length; i++) {
// is it selected?
if (issues[i].selected) {
// yes, build a list item
output += "<li>" + issues[i].value + "</li>";
}
}
// set the list's content
document.getElementById("issue-type").innerHTML = output;
}
<body>
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
</ul>
</body>
How I would have coded it
const issueSelect = document.getElementById("issue");
// listen for a change
issueSelect.addEventListener("change", selChanged);
function selChanged() {
const selectedOpts = issueSelect.querySelectorAll("option:checked");
const output = [...selectedOpts].map(opt => `<li>${opt.value}</li>`).join('');
document.getElementById("issue-type").innerHTML = output;
}
<body>
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
</ul>
</body>
Here is one solution and I commented each line.
let output = '';
let issues = document.querySelector("#issue");
let issue_types = document.querySelector("#issue-type");
issues.addEventListener("change", function(e) { //change event listener to check for when the select is changed
issue_types.innerHTML = ""; //empties destination div
let options = e.target.selectedOptions; //grabs the selected options
options = Array.from(options).map(({ value }) => value); //converts the selected options to an array of values
options.forEach(function(opt){ //loops through the options
let li = document.createElement("li"); //creates a LI element
li.innerHTML = opt; //sets the innerHTML of the list item to the option
issue_types.appendChild(li) //appends the list to the destination UL
});
});
<label for="issue">Issue Type:</label>
<select multiple="multiple" name="issue" id="issue">
<option value="passport">passport</option>
<option value="selfie">selfie</option>
<option value="nationalId">nationalId</option>
</select>
<p> you are missing the following information:</p>
<ul id="issue-type">
</ul>

Javascript onchange with select element

I am trying to create a dropdown menu and when one option is selected a div appears. All the divs are set to display none, When one option is clicked I would like to change that style to display: block. So far I have used onchange but that only applies to the whole select element and not the specific options.
So what are my choices for changing the display to block when clicking on a certain option of a select element?
This is my code
#card1, #card2, #card3 {
display: none;
}
<select name="" id="" onchange="showOnChange()">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
<div id="card1">card1</div>
<div id="card2">card2</div>
<div id="card3">card3</div>
<script>
function showOnChange() {
document.getElementById('card1').style.display = "block";
}
</script>
I little bit updated your html and js function as well, see below please if work for you:
<select name="" id="" onChange="showOnChange(this)">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
And JS part:
function showOnChange(self) {
var allDiv = self.options;
for(var i = 0; i < allDiv.length; i++){
document.getElementById(allDiv[i].value).style.display = "none";
}
document.getElementById(self.value).style.display = 'block';
}
You could get the value from the card that you select and show that id
#card1, #card2, #card3 {
display: none;
}
<select name="" id="" onchange="showOnChange(this)">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
<div id="card1">card1</div>
<div id="card2">card2</div>
<div id="card3">card3</div>
<script>
function showOnChange(element) {
var value = element.value
document.getElementById(value).style.display = "block";
}
</script>
Note the this keyword added to the select onchange function
You can catch which option is selected in your onChange and then based on that you can show your div.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<style>
#card1{
display:block;
}
#card2, #card3 {
display: none;
}
</style>
<select name="" id="slct" onchange="showOnChange(event)">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
<div id="card1">card1</div>
<div id="card2">card2</div>
<div id="card3">card3</div>
<script>
function showOnChange(e) {
var elem = document.getElementById("slct");
var value = elem.options[elem.selectedIndex].value;
if(value == "card1")
{
document.getElementById('card1').style.display = "block";
document.getElementById('card2').style.display = "none";
document.getElementById('card3').style.display = "none";
}
else if(value == "card2")
{
document.getElementById('card1').style.display = "none";
document.getElementById('card2').style.display = "block";
document.getElementById('card3').style.display = "none";
}
else if(value == "card3")
{
document.getElementById('card1').style.display = "none";
document.getElementById('card2').style.display = "none";
document.getElementById('card3').style.display = "block";
}
}
</script>
</body>
</html>
Please check below link for the jsbin
https://jsbin.com/memilufogi/edit?html,output
you have to pass the value of select in showOnChange function or you can get in the function as well
function showOnChange(val) {
document.getElementById(val).style.display = "block";
}
#card1, #card2, #card3 {
display: none;
}
<select name="" id="" onchange="showOnChange(this.value)">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
<div id="card1">card1</div>
<div id="card2">card2</div>
<div id="card3">card3</div>
You could give all your divs a class, so that you can query the DOM by that class and hide them all. Then you look for the div whose ID matches the selected option and show it.
See the attached snippets.
document.getElementById('cardMenu').addEventListener('change', showOnChange);
function showOnChange(evt) {
// capture the target of the change event : select element
var cardMenu = evt.target;
// hide all cards
var cards = document.getElementsByClassName('card');
for (var i = 0; i < cards.length; i++) {
cards[i].style.display = "none";
}
// show the card whose id matches the selected value
document.getElementById(cardMenu.value).style.display = "block";
}
#card1,
#card2,
#card3 {
display: none;
}
<select name="cardMenu" id="cardMenu">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
<div class="card" id="card1">card1</div>
<div class="card" id="card2">card2</div>
<div class="card" id="card3">card3</div>
CSS
<style>
#card1, #card2, #card3 {
display: none;
}
</style>
HTML
<!-- Pass current selected value -->
<select name="" id="" onchange="showOnChange(this.value)">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
<!-- Add common class in every property -->
<!-- Class will help to reset all class display none when selected new option -->
<div id="card1" class="div_cls">card1</div>
<div id="card2" class="div_cls">card2</div>
<div id="card3" class="div_cls">card3</div>
JS
<script>
function showOnChange(div_id) {
var div_id = div_id;
/*
Getting lenght of all div
*/
var div_len = document.getElementsByClassName("div_cls").length;
/* run loop and reset all div display to none*/
for(i=0; i< div_len; i++) {
document.getElementsByClassName("div_cls")[i].style.display = "none";
}
// Now set block for current selected option
document.getElementById(div_id).style.display = "block";
}
</script>
Just with javascript:
function showOnChange() {
var whichOp = document.getElementById("sel").selectedIndex;
var c = document.getElementsByClassName("card");
for (len = 0;len < c.length; len++)
c[len].style.display = "none";
c[whichOp].style.display = "block";
}
#card1, #card2, #card3 {
display: none;
margin-top: 10px;
}
<select name="" id="sel" onchange="showOnChange()">
<option value="card1">card1</option>
<option value="card2">card2</option>
<option value="card3">card3</option>
</select>
<div id="card1" class="card">card1</div>
<div id="card2" class="card">card2</div>
<div id="card3" class="card">card3</div>

How to add another identical dropdown list?

Hi I have this very simple code to go along with a revision timetabler I am creating for a school project. It's just a simple dropwdown list that allows the user to select the subjects they do. How would I add a button that creates another identical list below so the user can add more than 1 subject if they wish?
<!doctype html>
<html>
<head>
<title>Select your subjects</title>
<select id="subject1" name="subject1">
<option value="Maths">Maths</option>
<option value="Physics">Physics</option>
<option value="English">English</option>
<option value="Compting">Computing</option>
</select>
</head>
<body>
</body>
</html>
Something like this?
Note that I've changed the name of the select to be an array[]. So when you're processing the data on the server end, just note you'll be handling an array of element and not subject1, subject2, subject3, etc.
function addCourse() {
document.getElementById("subjects").innerHTML += '\
<br><select name="subject[]">\
<option value="Maths">Maths</option>\
<option value="Physics">Physics</option>\
<option value="English">English</option>\
<option value="Compting">Computing</option>\
</select>';
}
addCourse();
document.getElementById("add").addEventListener("click", addCourse);
<!doctype html>
<html>
<head>
</head>
<body>
<form method="post" action="">
<title>Select your subjects</title>
<div id="subjects">
</div>
</form>
<input type="button" id="add" value="Add Course">
</body>
</html>
I'd actually recommend a dropdown to specify how many lists the user wants. So something like this would be better:
var maxCourses = 5;
var select = document.getElementById("num");
var subjects = document.getElementById("subjects");
var previous = 1;
for (var i = 1; i <= maxCourses; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
select.appendChild(opt);
}
select.addEventListener("change", function() {
var diff = select.value - previous;
for (var i = 0; i < Math.abs(diff); i++)
if (diff > 0)
addCourse();
else
removeCourse();
previous = select.value;
});
function addCourse() {
subjects.innerHTML += '\
<select name="subject[]">\
<option value="Maths">Maths</option>\
<option value="Physics">Physics</option>\
<option value="English">English</option>\
<option value="Compting">Computing</option>\
</select>';
}
function removeCourse() {
subjects.removeChild(subjects.lastChild);
}
addCourse();
select {
display: block;
}
<!doctype html>
<html>
<head>
</head>
<body>
<form method="post" action="">
<title>Select your subjects</title>
Number of Courses:
<select id="num"></select><br>
<div id="subjects">
</div>
</form>
</body>
</html>

HTML5 Drop down with list

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);
}

HTML select dropdownlist with javascript function

This is how far I got:
<head>
<script type="text/javascript">
function showonlyone(thechosenone) {
var article = document.getElementsByTagName("div");
for(var x=0; x<article.length; x++) {
name = article[x].getAttribute("name");
if (name == 'article') {
if (article[x].id == thechosenone) {
article[x].style.display = 'block';
}
else {
article[x].style.display = 'none';
}
}
}
}
</script>
</head>
<form>
<select>
<option SELECTED>Choose one</option>
<option value="javascript:showonlyone(id1)">First</option> <!-- That's probably wrong -->
<option value="javascript:showonlyone(id2)">Second</option>
</select>
</form>
<div name="article" id="id1" style="display:none;">
First one selected
</div>
<div name="article" id="id2" style="display:none;">
Second one selected
</div>
Here is what it should do:
Create a dropdownlist (with 3 Values)
If you click on "First" it should only show the of the content of <div id="id1">
If you click on "Second" it should only show the of the content of <div id="id2">
I know that this can't work like this. But I do not know how I can get this working.
There might be a easier way than this javascript function but it has to be this way.
Thank you for your help
Use a onchange event handler instead:
Update your <select> to <select onchange="showonlyone(this)">.
Change your <option> values to only the IDs - not JavaScript calls.
Update your JavaScript to accept the HTMLSelectElement (which will be passed-in by the this, above). (Yes, you were correct here.)
From the chosen HTMLSelectElement, ask it for its value.
Here is a fixed, working version: http://jsfiddle.net/YRF6u/
Also included here:
<head>
<script type="text/javascript">
function showonlyone(selector) {
var thechosenone = selector.value;
var article = document.getElementsByTagName("div");
for(var x=0; x<article.length; x++) {
name = article[x].getAttribute("name");
if (name == 'article') {
if (article[x].id == thechosenone) {
article[x].style.display = 'block';
}else{
article[x].style.display = 'none';
}
}
}
}
</script>
</head>
<form>
<select onchange="showonlyone(this)">
<option SELECTED>Choose one</option>
<option value="id1">First</option>
<option value="id2">Second</option>
</select>
</form>
<div name="article" id="id1" style="display:none;">
First one selected
</div>
<div name="article" id="id2" style="display:none;">
Second one selected
</div>
I would not consider this production-ready code, but it should be sufficient enough to solve your current round of questions.

Categories