javascript shows all associated DIVs on a dropdown box select - javascript

I am new to javascript and must have looked at almost all of the previous questions here and elsewhere related to this question and none seem to do the trick because they use asp, php, Ajax etc.
I use jQuery code for several other items on the page and have found that their css can cause issues with my pages and am not keen on using it either.
In my case, is there a way to select a country from a drop down box and then display a dropdown box with the states or provinces for that country. My code is shown below but when I run it, it shows all DIVs and not just the DIV that applies to the country selected. If a country has no states/province it will display nothing but passes a value of 0.
I'd like to know what is wrong with this code.
Second question is, the page starts with a default country and its states/provinces but since I use onChange on the country select, the javascript would not be triggered because initially there is no change. Regardless, even when I do change the country from its default, all DIVs are displayed anyway.
Is it possible to show the states/provinces for the default country and still use javascript for any change made to the default selection. It does not show this in the sample below, but the values for the countries and the associated states/provinces come from a database and can therefore not be incorporated in the javascript.
Any help or suggestions will be greatly appreciated.
<TABLE>
<TR><TD>Country</DIV></TD>
<TD><SELECT NAME="countryid" onChange="showstate(this.options[this.selectedIndex].value)">
<OPTION VALUE="NONE">Select a country</OPTION>
<OPTION VALUE="CA" SELECTED>Canada</OPTION>
<OPTION VALUE="US">United States</OPTION>
<OPTION VALUE="ES">Spain</OPTION>
</SELECT></TD>
</TR>
<script>
function showstate(country) {
if (country == "CA") {
hiddenDivUS.style.display='none';
hiddenDivNONE.style.display='none';
hiddenDivCA.style.display='block';
}
else {
if (country == "US") {
hiddenDivCA.style.display='none';
hiddenDivNONE.style.display='none';
hiddenDivUS.style.display='block';
}
else {
hiddenDivCA.style.display='none';
hiddenDivUS.style.display='none';
hiddenDivNONE.style.display='block';
}
}
</script>
<DIV ID="hiddenDivNONE" STYLE="display:none">
<TR><TD><DIV CLASS="inputlabel">Prov/State</DIV></TD>
<TD><INPUT TYPE="hidden" NAME="provid" VALUE="0"></TD>
</TR>
</DIV>
<DIV ID="hiddenDivCA" STYLE="display:none">
<TR><TD><DIV CLASS="inputlabel">Prov/State</DIV></TD>
<TD><SELECT NAME="provid">
<OPTION VALUE="101">British Columbia</OPTION>
.......
<OPTION VALUE="165">Yukon Territories</OPTION>
</SELECT></TD>
</TR>
</DIV>
<DIV ID="hiddenDivUS" STYLE="display:none">
<TR><TD><DIV CLASS="inputlabel">Prov/State</DIV></TD>
<TD><SELECT NAME="provid">
<OPTION VALUE="201">Alaska</OPTION>
.......
<OPTION VALUE="265">Wyoming</OPTION>
</SELECT></TD>
</TR>
</DIV>
</TABLE>
Instead of listing the proper DIV it shows all three of them

First off, careful with your capitals.
Secondly try to keep all js at the bottom of the page.
This code is using ES6 so you might wanna check if it will work in all browsers but you can see whats going on.
el.classList is supported by most browsers however add,remove and toggle are not (were not.. not sure now)
I have used some regex to grab all elements using the id state_ so we can hide them, then we target the exact one to make it visible, you can probably clean that up also.
<style>
.hidden {
display: none;
}
</style>
<select name="countryid" onChange="showState(event)">
<option value="">Select a country</option>
<option value="ca">Canada</option>
<option value="us">United States</option>
<option value="es">Spain</option>
</select>
<div id="state_ca" class="hidden">
This is hidden unless Canada is selected.
</div>
<div id="state_us" class="hidden">
This is hidden unless America is selected.
</div>
<script>
function showState(event) {
const countryCode = event.target.value;
const states = document.querySelectorAll('[id^=state_]');
const el = document.getElementById(`state_${countryCode}`);
states.forEach(el => {
if (el.classList.contains('hidden')) {
return;
}
el.classList.add('hidden');
});
if (el) {
el.classList.remove('hidden');
}
}
</script>

according to me this can be the answer to your problem. You can make a few changes in the code which I have not done.
function addStates() {
var selectCountry = document.getElementById("selectCountry").value;
console.log(selectCountry);
var selectState = document.getElementById("selectState");
if (selectCountry == "india") {
var option1 = document.createElement("option");
option1.value = "punjab";
option1.text = "Punjab";
selectState.add(option1);
var option2 = document.createElement("option");
option2.value = "karnataka";
option2.text = "Karnataka";
selectState.add(option2);
} else if (selectCountry == "usa") {
var option1 = document.createElement("option");
option1.value = "florida";
option1.text = "Florida";
selectState.add(option1);
var option2 = document.createElement("option");
option2.value = "california";
option2.text = "California";
selectState.add(option2);
}
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div>
<div>
<span>Select a country: </span>
</div>
<div>
<select onchange="addStates()" id="selectCountry">
<option value="" selected disabled>Please select a country</option>
<option value="india">India</option>
<option value="usa">USA</option>
</select>
</div>
</div>
<div>
<div>
<span>Please select a state: </span>
</div>
<div>
<select id="selectState">
</select>
</div>
</div>
</body>
</html>

I figured out how to get the desired result (see code below)
<!DOCTYPE HTML>
<HTML>
<HEAD>
<script>
function showStates(country)
{
if (country == "101")
{ document.getElementById('CAprov').style.display='block';
document.getElementById('Default').style.display='none';
document.getElementById('USstate').style.display='none';
document.getElementById('NoProv').style.display='none';
}
else if (country == "102")
{ document.getElementById('CAprov').style.display='none';
document.getElementById('Default').style.display='none';
document.getElementById('USstate').style.display='block';
document.getElementById('NoProv').style.display='none';
}
else
{ document.getElementById('CAprov').style.display='none';
document.getElementById('USstate').style.display='none';
document.getElementById('Default').style.display='none';
document.getElementById('NoProv').style.display='block';
}
return false;
}
</script>
</HEAD>
<BODY TOPMARGIN="0" LEFTMARGIN="0" MARGINHEIGHT="0" MARGINWIDTH="0" BORDER="0">
<FORM METHOD="post">
<TABLE>
<TR><TD>Country</TD>
<TD><SELECT NAME="country" id="country" onChange="showStates(this.options[this.selectedIndex].value);">
<OPTION VALUE="101" SELECTED>Canada</OPTION>
<OPTION VALUE="102">United States</OPTION>
<OPTION VALUE="314">Germany</OPTION>
</SELECT></TD></TR>
<TR ID="Default" STYLE="display: block;"><TD>Province</TD>
<TD><SELECT NAME="provid">
<OPTION VALUE="0">Select province</OPTION>
<OPTION VALUE="139">Newfoundland/Labrador</OPTION>
<OPTION VALUE="143">Nova Scotia</OPTION>
<OPTION VALUE="134">New Brunswick</OPTION>
<OPTION VALUE="149">Prince Edward Island</OPTION>
</SELECT></TD></TR>
<TR ID="CAprov" STYLE="display: none;"><TD>Province</TD>
<TD><SELECT NAME="provid">
<OPTION VALUE="0">Select province</OPTION>
<OPTION VALUE="139">Newfoundland/Labrador</OPTION>
<OPTION VALUE="143">Nova Scotia</OPTION>
<OPTION VALUE="134">New Brunswick</OPTION>
<OPTION VALUE="149">Prince Edward Island</OPTION>
</SELECT></TD></TR>
<TR ID="USstate" STYLE="display: none;"><TD>State</TD>
<TD><SELECT NAME="provid">
<OPTION VALUE="0">Select state</OPTION>
<OPTION VALUE="102">Alabama</OPTION>
<OPTION VALUE="105">Arizona</OPTION>
<OPTION VALUE="106">Arkansas</OPTION>
<OPTION VALUE="108">California</OPTION>
</SELECT></TD></TR>
<TR ID="NoProv" STYLE="display: none;"><TD>Prov/State</TD>
<TD><INPUT TYPE="hidden" NAME="provid" VALUE="0"> </TD></TR>
</TABLE>
</FORM>
</BODY>
</HTML>

Related

Multiple drop down boxes?

I'm trying to get multiple drop down boxes to open when selecting different prompts from an original drop down menu.
So for example the original drop box would say "Continent" then drop down to a list of continents, when you select a continent a new box opens that asks you "Country" then you select a country and a new drop box opens to select a state.
I've been using this template
<script type="text/javascript">
function CheckDepartment(val){
var element=document.getElementById('othercolor');
if(val=='others')
element.style.display='block';
else
element.style.display='none';}
function CheckOption(val){
var element=document.getElementById('misc')
if(val=='misc')
element.style.display='block';
else
element.style.display='block';
}
</script>
</head>
<body>
<select name="color" onchange='CheckDepartment(this.value);'>
<option>pick a color</option>
<option value="red">RED</option>
<option value="blue">BLUE</option>
<option value="others">others</option>
</select>
<select name="othercolor" id="othercolor" onchange='CheckOption(this.value)' style='display:none;'/>
<option value=""></option>
<option value="hi">hi</option>
<option value="misc" id="misc" >misc</option>
</select>
<select name="third" style='display:none;'>
<option value=""></option>
<option value="first">first</option>
<option value="second">second</option>
</select>
but I can't get a third drop box to open when selecting an option from the second drop box.
edit: third box. I think i deleted my last try so this was kinda a recreation of it from what I remembered. I'm also incredibly new at all of this and don't know if anything I tried makes sense.
Here's a simplified demo.
(It assumes only a "yes" value should trigger the display of the next dependent dropdown.)
const
select1 = document.getElementById("select1"),
select2 = document.getElementById("select2");
document.addEventListener("change", handleDropdownDisplay);
function handleDropdownDisplay(event) {
let changedElement = event.target;
if ((changedElement != select1) && (changedElement != select2)) {
return;
}
if (changedElement.value == "yes") {
changedElement.parentElement.nextElementSibling.classList.remove("hidden");
} else {
changedElement.parentElement.nextElementSibling.classList.add("hidden");
}
}
div {
margin-bottom: 0.5em;
}
.hidden {
display: none;
}
<div>
<label for="select1">Show level 2?</label>
<select id="select1">
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
</div>
<div class="hidden">
<label for="select2">Show level 3?</label>
<select id="select2">
<option value="no">No</option>
<option value="yes">Yes</option>
</select>
</div>
<div class="hidden">
<label for="select3">Would your rather</label>
<select id="select3">
<option value="brains">Eat monkey brains</option>
<option value="vba">Write code in VBA</option>
</select>
</div>
(Btw, level 3 doesn't automatically become hidden whenever level 2 becomes hidden. This is probably functionality you'll want to add.)

How do I hide options within a range of selects based upon changes in different select?

Related JSFiddle
<form id="calendar_form">
<div class="day1">
Day 1
<table class="selector_table">
<select name="select1">
<option></option>
<option value="optionA">PersonA</option>
<option value="optionB">PersonB</option>
</select>
<select name="select2">
<option></option>
<option value="optionA">PersonA</option>
<option value="optionB">PersonB</option>
</select>
</table>
</div>
<br>
<div class="day2">
Day 2
<table class="selector_table">
<select name="select3">
<option></option>
<option value="optionA">PersonA</option>
<option value="optionB">PersonB</option>
</select>
<select name="select4">
<option></option>
<option value="optionA">PersonA</option>
<option value="optionB">PersonB</option>
</select>
</table>
</div>
</form>
<script>
$("select").change(function(){
var selectThatWasChanged = $(this).attr('id');
var valueToRemove = $(this).val();
var dayWorkingWith = $(this).closest('.selector_table');
$('option', dayWorkingWith).not('#' + selectThatWasChanged + ' option');
$('option[value="' + valueToRemove + '"]').not('#' + selectThatWasChanged + ' option').hide();
});
</script>
I've been playing with this for an hour, and I'm frustrated. sigh. What I'm trying to accomplish is this: If PersonA is selected in Day1, he should not be available to pick again anywhere in Day1. However, PersonA should still be available on Day2.
Currently if PersonA is selected, PersonA is removed from all other selects. I tried to hone in on just the relevant selects by using the closest('.selector_table').
What am I doing wrong?
Thank you so much, in advance!
Bonus basic question: would it be tremendously more work to "undo" the change. For instance, if someone selects PersonA it hides PersonA as described, but then if PersonB is selected thereafter on the same select, it undoes that change and PersonA becomes available again?
Apply change event to the select Element, get the sibling select and disable it's matching option element.
$("select").change(function() {
const selectedOptionVal = $(this).find(":selected")[0].value;
const sibSelectEle = $(this).siblings('select');
sibSelectEle.children('option').each(function(_, option) {
if (selectedOptionVal == option.value) {
$(option).attr("disabled", true);
} else {
$(option).attr("disabled", false);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="calendar_form">
<div class="day1">
Day 1
<table class="selector_table">
<select name="select1">
<option></option>
<option value="optionA">PersonA</option>
<option value="optionB">PersonB</option>
</select>
<select name="select2">
<option></option>
<option value="optionA">PersonA</option>
<option value="optionB">PersonB</option>
</select>
</table>
</div>
<br>
<div class="day2">
Day 2
<table class="selector_table">
<select name="select3">
<option></option>
<option value="optionA">PersonA</option>
<option value="optionB">PersonB</option>
</select>
<select name="select4">
<option></option>
<option value="optionA">PersonA</option>
<option value="optionB">PersonB</option>
</select>
</table>
</div>
</form>

Select option value based on another select option in dynamic table

I have a table that changes the number of rows
<html>
<head>
<title>no Title</title>
<script type="text/javascript">
//what to do?
</script>
</head>
<body>
<datalist>
//land
//water
//air
//what to do?
</datalist>
<table id="animal">
<tr>
<th>Animal Category</th>
<th>Select Animal</th>
</tr>
<tr>
<td>
<select>
<option selected>Please select</option>
<option value="land">Land</option>
<option value="air">Air</option>
<option value="water">Water</option>
</select>
</td>
<td>
<select>
<option selected>Please select</option>
//what to do?
</select>
</td>
</tr>
<tr>
<td>
<select>
<option selected>Please select</option>
<option value="land">Land</option>
<option value="air">Air</option>
<option value="water">Water</option>
</select>
</td>
<td>
<select>
<option selected>Please select</option>
//what to do?
</select>
</td>
</tr>
</table>
<script src="myProject/js/jquery.min.js"></script>
</body>
</html>
Let's say there are currently 2 rows, then in each row, there is 'Select Animal' which can be selected according to the 'Animal Category' option.
For example, I chose 'land' in 'Animal category' then what appears in 'Select Animal' is -> cat, dog, chicken
For example I have 3 lists (land, air, water)
land -> cat, dog, chicken, etc
water -> fish, octopus, shrimp, etc
air -> bird, etc
Every list I want to place in the datalist because it can change in number, I've download jquery library. where do I start ?
The easiest way is to make just two selects and add some classes on it.
Then filter by classes or attributes. I've done by class on this example.
document.getElementById("main_select").onchange = function(){
let selector = document.getElementById('main_select');
let value = selector[selector.selectedIndex].value;
let nodeList = document.getElementById("sub_select").querySelectorAll("option");
nodeList.forEach(function(option){
if(option.classList.contains(value)){
option.style.display="block";
}else{
option.style.display="none";
}
});
}
<html>
<head>
<title>no Title</title>
</head>
<body>
<table id="animal">
<tr>
<td>
<select id="main_select">
<option selected>Please select</option>
<option value="land">Land</option>
<option value="air">Air</option>
<option value="water">Water</option>
</select>
</td>
<td>
<select id="sub_select">
<option selected>Please select</option>
<option class="land" value="cat">cat</option>
<option class="land" value="dog">dog</option>
<option class="land" value="chicken">chicken</option>
<option class="water" value="fish">fish</option>
<option class="water" value="octopus">octopus</option>
</select>
</td>
</tr>
</table>
Store your animals inside an Object literal
And than you could do like:
const categories = {
land: ["cat", "dog", "chicken"],
water: ["fish", "octopus", "shrimp"],
air: ["bird", "dragon"]
};
const options = Object.keys( categories ).map(pr => `<option value="${pr}">${pr}</option>`);
$("[data-target]").append( options ).on('change', function() {
const $targ = $(this.dataset.target).prop("disabled", false);
$targ.find("option:not(:disabled)").remove(); // Remove all but first option
$targ.append(categories[this.value].map(val => `<option value="${val}">${val}</option>`)); // Append new options
});
select {text-transform: capitalize;}
<select data-target="#anim"><option selected disabled>Select Category</option></select>
<select id="anim" disabled><option selected disabled>Select animal</option></select>
<script src="//code.jquery.com/jquery-3.4.1.min.js"></script>

Make image change with selecting different option in dropdown - Javascript / Html

I have a system where you are able to choose a car. You can then choose the transmission and color. Different cars and transmissions bring up different colors. Not sure how to make an image appear of a car when a color is chosen. So for example I choose the rs6 and automatic and then the black color. I would then want an image to appear depending on the color chosen. How would I program it so different cars and colors bring up different images. Im relatively new to coding. Any help would be aprreciated.
HTML
<!DOCTYPE html>
<html><head>
<title></title>
</head>
<body>
<form name="CarConfigurator">
<select id="car" name="Car_make">
<option value="" selected="selected">Which car?</option>
<option value="car1">Audi RS6</option>
<option value="car2">BMW M4</option>
<option value="car3">Mercedes C63 AMG</option>
</select>
<br>
<br>
<select id="trans" name="A_M">
<option value="" selected="selected">What trans?</option>
<option value="auto">Automatic</option>
<option value="man">Manual</option>
</select>
<br>
<br>
<select id="color" name="Color">
<option value="" selected="selected">What Color?</option>
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
<option value="white">White</option>
<option value="green">Green</option>
</select>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1 /jquery.min.js"/
</script>
<script src="configurator.js"></script>
</body>
</html>
Javascript
$("#car").change(function () {
transmission();
});
$("#trans").change(function () {
transmission();
});
function transmission() {
if ($("#car").val() == "car1" && $("#trans").val() == "auto") {
$("option[value$='red']").hide();
$("option[value$='white']").hide();
$("option[value$='green']").hide();
} else {
$("option[value$='red']").show();
$("option[value$='white']").show();
$("option[value$='green']").show();
}
}
For now it is only working for Audi - Automatic - black and blue to show you the basic idea but it is repeating code and you can do the same for the rest of the cars too.
In this example I am setting the src of the image as the car selected. For example if you select car1 and man and red then src of the image as car1manred.jpg, also I'm changing the alt attribute as well so that you can see the change.
you have to do a lot of manual work. I have created an object for the data that will determine how many cars you have in each category. It would be better if you use JSON for that.
Also I have made car1autoblack (which gets the src of the images) as an array but you can make it as an object and include other things about the cars in this category. for example name, price, availability and much more
$("#car").change(function () {
transmission();
selection();
});
$("#trans").change(function () {
transmission();
selection();
});
$("#color").change(function () {
selection();
});
var cars = {
car1autoblack:["car1auto1black1.png","car1auto1black2.jpg"],
car1autoblue:["car1auto1blue1.png","car1auto1blue2.jpg","car1auto1blue3.jpeg"]
}
function transmission() {
if ($("#car").val() == "car1" && $("#trans").val() == "auto") {
$("option[value$='red']").hide();
$("option[value$='white']").hide();
$("option[value$='green']").hide();
} else {
$("option[value$='red']").show();
$("option[value$='white']").show();
$("option[value$='green']").show();
}
}
function selection(){
if ($("#car").val() && $("#trans").val() && $("#color").val()) {
var carVal = $("#car").val();
var transVal = $("#trans").val();
var colorVal = $("#color").val();
var combineVal = carVal+transVal+colorVal;
//var imageLink = combineVal+".jpg";
//$("#showImg").attr("src", imageLink);
//$("#showImg").attr("alt", imageLink);
//console.log(cars[combineVal]);
var inputDivHTML = "";
var car = cars[combineVal];
for(i in car){
inputDivHTML += "<img class='showImg' src='"+car[i]+"' alt='"+car[i]+"'/>";
}
$(".imageHere").html(inputDivHTML);
}
}
img.showImg{
width:150px;
height:70px;
margin:10px 3px;
border:1px solid red;
float:left;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="CarConfigurator">
<select id="car" name="Car_make">
<option value="" selected="selected">Which car?</option>
<option value="car1">Audi RS6</option>
<option value="car2">BMW M4</option>
<option value="car3">Mercedes C63 AMG</option>
</select>
<br>
<br>
<select id="trans" name="A_M">
<option value="" selected="selected">What trans?</option>
<option value="auto">Automatic</option>
<option value="man">Manual</option>
</select>
<br>
<br>
<select id="color" name="Color">
<option value="" selected="selected">What Color?</option>
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="red">Red</option>
<option value="white">White</option>
<option value="green">Green</option>
</select>
</form>
<div class="imageHere">
<img class="showImg" src="http://www.chinabuddhismencyclopedia.com/en/images/thumb/b/b8/Nature.jpg/240px-Nature.jpg"/>
<img class="showImg" src="http://www.chinabuddhismencyclopedia.com/en/images/thumb/b/b8/Nature.jpg/240px-Nature.jpg"/>
<img class="showImg" src="http://www.chinabuddhismencyclopedia.com/en/images/thumb/b/b8/Nature.jpg/240px-Nature.jpg"/>
</div>

How to use onClick() or onSelect() on option tag in a JSP page?

How to use onClick() or onSelect() with option tag? Below is my code in which I tried to implement that, but it is not working as expected.
Note: where listCustomer domain object list getting in JSP page.
<td align="right">
<select name="singleSelect" ">
<c:forEach var="Customer" items="${listCustomer}" >
<option value="" onClick="javascript:onSelect(this);> <c:out value="${Customer}" /></option>
</c:forEach>
</select>
</td>
How do I modify it to detect that an option is selected?
Neither the onSelect() nor onClick() events are supported by the <option> tag. The former refers to selecting text (i.e. by clicking + dragging across a text field) so can only be used with the <text> and <textarea> tags. The onClick() event can be used with <select> tags - however, you probably are looking for functionality where it would be best to use the onChange() event, not onClick().
Furthermore, by the look of your <c:...> tags, you are also trying to use JSP syntax in a plain HTML document. That's just... incorrect.
In response to your comment to this answer - I can barely understand it. However, it sounds like what you want to do is get the value of the <option> tag that the user has just selected whenever they select one. In that case, you want to have something like:
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
Even more simplified: You can pass the value attribute directly!
<html>
<head>
<script type="text/javascript">
function changeFunc(i) {
alert(i);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc(value);">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
The alert will either return 1 or 2.
The answer you gave above works but it is confusing because you have used two names twice and you have an unnecessary line of code. you are doing a process that is not necessary.
it's a good idea when debugging code to get pen and paper and draw little boxes to represent memory spaces (i.e variables being stored) and then to draw arrows to indicate when a variable goes into a little box and when it comes out, if it gets overwritten or is a copy made etc.
if you do this with the code below you will see that
var selectBox = document.getElementById("selectBox");
gets put in a box and stays there you don't do anything with it afterwards.
and
var selectBox = document.getElementById("selectBox");
is hard to debug and is confusing when you have a select id of selectBox for the options list . ---- which selectBox do you want to manipulate / query / etc is it the local var selectBox that will disappear or is it the selectBox id you have assigned to the select tag
your code works until you add to it or modify it then you can easily loose track and get all mixed up
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectBox = document.getElementById("selectBox");
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
a leaner way that works also is:
<html>
<head>
<script type="text/javascript">
function changeFunc() {
var selectedValue = selectBox.options[selectBox.selectedIndex].value;
alert(selectedValue);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunc();">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
and it's a good idea to use descriptive names that match the program and task you are working on am currently writing a similar program to accept and process postcodes using your code and modifying it with descriptive names the object is to make computer language as close to natural language as possible.
<script type="text/javascript">
function Mapit(){
var actualPostcode=getPostcodes.options[getPostcodes.selectedIndex].value;
alert(actualPostcode);
// alert is for debugging only next we go on to process and do something
// in this developing program it will placing markers on a map
}
</script>
<select id="getPostcodes" onchange="Mapit();">
<option>London North Inner</option>
<option>N1</option>
<option>London North Outer</option>
<option>N2</option>
<option>N3</option>
<option>N4</option>
// a lot more options follow
// with text in options to divide into areas and nothing will happen
// if visitor clicks on the text function Mapit() will ignore
// all clicks on the divider text inserted into option boxes
</select>
in this example de select tag is named as: aula_clase_cb
<select class="form-control" id="aula_clase_cb" >
</select>
document.getElementById("aula_clase_cb").onchange = function(e){
id = document.getElementById('aula_clase_cb').value;
alert("id: "+id);
};
<div class="form-group">
<script type="text/javascript">
function activa(){
if(v==0)
document.formulario.vr_negativo.disabled = true;
else if(v==1)
document.formulario.vr_negativo.disabled = true;
else if(v==2)
document.formulario.vr_negativo.disabled = true;
else if(v==3)
document.formulario.vr_negativo.disabled = true;
else if(v==4)
document.formulario.vr_negativo.disabled = true;
else if(v==5)
document.formulario.vr_negativo.disabled = true;
else if(v==6)
document.formulario.vr_negativo.disabled = false;}
</script>
<label>¿Qué tipo de vehículo está buscando?</label>
<form name="formulario" id="formulario">
<select name="lista" id="lista" onclick="activa(this.value)">
<option value="0">Vehiculo para la familia</option>
<option value="1">Vehiculo para el trabajo</option>
<option value="2">Camioneta Familiar</option>
<option value="3">Camioneta de Carga</option>
<option value="4">Vehiculo servicio Publico</option>
<option value="5">Vehiculo servicio Privado</option>
<option value="6">Otro</option>
</select>
<br />
<input type="text" id="form vr_negativo" class="form-control input-xlarge" name="vr_negativo"/>
</form>
</div>
You can change selection in the function
window.onload = function () {
var selectBox = document.getElementById("selectBox");
selectBox.addEventListener('change', changeFunc);
function changeFunc() {
alert(this.value);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Selection</title>
</head>
<body>
<select id="selectBox" onChange="changeFunc();">
<option> select</option>
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
<html>
<head>
<title>Cars</title>
</head>
<body >
<h1>Cars</h1>
<p>Name </p>
<select id="selectBox" onchange="myFunction(value);">
<option value="volvo" >Volvo</option>
<option value="saab" >Saab</option>
<option value="mercedes">Mercedes</option>
</select>
<p id="result"> Price : </p>
<script>
function myFunction($value)
{
if($value=="volvo")
{document.getElementById("result").innerHTML = "30L";}
else if($value=="saab")
{document.getElementById("result").innerHTML = "40L";}
else if($value=="mercedes")
{document.getElementById("result").innerHTML = "50L";}
}
</script>
</body>
</html>```
Other option, for similar example but with anidated selects, think that you have two select, the name of the first is "ea_pub_dest" and the name of the second is "ea_pub_dest_2", ok, now take the event click of the first and display the second.
<script>
function test()
{
value = document.getElementById("ea_pub_dest").value;
if ( valor == "value_1" )
document.getElementById("ea_pub_dest_nivel").style.display = "block";
}
</script>
Change onClick() from with onChange() in the . You can send the option value to a javascript function.
<select id="selector" onChange="doSomething(document.getElementById(this).options[document.getElementById(this).selectedIndex].value);">
<option value="option1"> Option1 </option>
<option value="option2"> Option2 </option>
<option value="optionN"> OptionN </option>
</select>
If you need to change the value of another field, you can use this:
<input type="hidden" id="mainvalue" name="mainvalue" value="0">
<select onChange="document.getElementById('mainvalue').value = this.value;">
<option value="0">option 1</option>
<option value="1">option 2</option>
</select>
example dom onchange usage:
<select name="app_id" onchange="onAppSelection(this);">
<option name="1" value="1">space.ecoins.beta.v3</option>
<option name="2" value="2">fun.rotator.beta.v1</option>
<option name="3" value="3">fun.impactor.beta.v1</option>
<option name="4" value="4">fun.colorotator.beta.v1</option>
<option name="5" value="5">fun.rotator.v1</option>
<option name="6" value="6">fun.impactor.v1</option>
<option name="7" value="7">fun.colorotator.v1</option>
<option name="8" value="8">fun.deluxetor.v1</option>
<option name="9" value="9">fun.winterotator.v1</option>
<option name="10" value="10">fun.eastertor.v1</option>
<option name="11" value="11">info.locatizator.v3</option>
<option name="12" value="12">market.apks.ecoins.v2</option>
<option name="13" value="13">fun.ecoins.v1b</option>
<option name="14" value="14">place.sin.v2b</option>
<option name="15" value="15">cool.poczta.v1b</option>
<option name="16" value="16" id="app_id" selected="">systems.ecoins.launch.v1b</option>
<option name="17" value="17">fun.eastertor.v2</option>
<option name="18" value="18">space.ecoins.v4b</option>
<option name="19" value="19">services.devcode.v1b</option>
<option name="20" value="20">space.bonoloto.v1b</option>
<option name="21" value="21">software.devcode.vpnfree.uk.v1</option>
<option name="22" value="22">software.devcode.smsfree.v1b</option>
<option name="23" value="23">services.devcode.smsfree.v1b</option>
<option name="24" value="24">services.devcode.smsfree.v1</option>
<option name="25" value="25">software.devcode.smsfree.v1</option>
<option name="26" value="26">software.devcode.vpnfree.v1b</option>
<option name="27" value="27">software.devcode.vpnfree.v1</option>
<option name="28" value="28">software.devcode.locatizator.v1</option>
<option name="29" value="29">software.devcode.netinfo.v1b</option>
<option name="-1" value="-1">none</option>
</select>
<script type="text/javascript">
function onAppSelection(selectBox) {
// clear selection
for(var i=0;i<=selectBox.length;i++) {
var selectedNode = selectBox.options[i];
if(selectedNode!=null) {
selectedNode.removeAttribute("id");
selectedNode.removeAttribute("selected");
}
}
// assign id and selected
var selectedNode = selectBox.options[selectBox.selectedIndex];
if(selectedNode!=null) {
selectedNode.setAttribute("id","app_id");
selectedNode.setAttribute("selected","");
}
}
</script>
In my case:
<html>
<head>
<script type="text/javascript">
function changeFunction(val) {
//Show option value
console.log(val.value);
}
</script>
</head>
<body>
<select id="selectBox" onchange="changeFunction(this)">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>
focus clears value, so select any value is a change and fires myFunc(this) and blur defocus for reselect
<html>
<head>
<script type="text/javascript">
function myFunc(el) {
//Show option value
console.log(el.value);
}
</script>
</head>
<body>
<select id="selectBox" onchange="myFunc(this);this.blur();" onfocus="this.selectedIndex = -1;">
<option value="1">Option #1</option>
<option value="2">Option #2</option>
</select>
</body>
</html>

Categories