Chosen select - filter <optgroup > using jquery - javascript

I am using chosen drop down in asp.net. Is there a way to filter optgroup ?
There is a radio button list control with values US and UK. I want to filter drop down based on user's radio button selection. If the 'US' is selected then drop down should only show US optgroup records.
Here is the jsfiddle;
http://jsfiddle.net/7ngftsq2/
This is what i have tried so far with no luck;
('#rbDistDiv input').change(function () {
// The one that fires the event is always the
// checked one; you don't need to test for this
var ddlDist = $('#VCSdistSelect_ddlDist'),
val = $(this).val(),
region = $('option:selected', this).text();
$('span > optgroup', ddlDist).unwrap();
if (val !== '%') {
$('optgroup:not([label="' + region + '"])', ddlDist).wrap('<span/>');
}
});

You should be able to do something similar to this:
$(".chosen").chosen({
width: '600px',
allow_single_deselect: true,
search_contains: true
});
let UK_optgroup = $("#optgroup-uk").clone();
let US_optgroup = $("#optgroup-us").clone();
let CA_optgroup = $("#optgroup-ca").clone();
function filterSelect(selectedRadio) {
switch(selectedRadio) {
case "US": return US_optgroup
case "UK": return UK_optgroup
case "CA": return CA_optgroup
}
}
$('[type="radio"]').on('change', function() {
// This is only here to clear the selected item that is shown on screen
// after a selection is made. You can remove this if you like.
$("#selected-item").html("");
// Everything from here down is needed.
$("#select")
.children()
.remove('optgroup');
$("#select")
.append(filterSelect(this.value))
.trigger("chosen:updated");
});
$("#select").on('change', function(event) {
$("#selected-item").html("Selected Item: <b>" + event.target.value + "</b>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/chosen/1.8.7/chosen.css" rel="stylesheet"/>
<table id="rbDistDiv" border="0">
<tbody>
<tr>
<td><input id="rbDistDiv_0" type="radio" name="rbDistDiv" value="US"><label for="rbDistDiv_0">US</label></td>
</tr>
<tr>
<td><input id="rbDistDiv_1" type="radio" name="rbDistDiv" value="UK"><label for="rbDistDiv_1">UK</label></td>
</tr>
<tr>
<td><input id="rbDistDiv_2" type="radio" name="rbDistDiv" value="CA"><label for="rbDistDiv_2">CA</label></td>
</tr>
</tbody>
</table>
<p id="selected-item"></p>
<select id="select" class="chosen">
<option value="" disabled selected>Select your option</option>
<optgroup id="optgroup-uk" label="UK">
<option value="Adrian">Adrian</option>
<option value="Alan">Alan</option>
<option value="Alan B">Alan B</option>
</optgroup>
<optgroup id="optgroup-us" label="US">
<option value="John">John</option>
<option value="Billy">Billy</option>
<option value="Chris">Chris</option>
</optgroup>
<optgroup id="optgroup-ca" label="CA">
<option value="Gabrielle">Gabrielle</option>
<option value="Maude">Maude</option>
<option value="Morgan">Morgan</option>
</optgroup>
</select>

Just hide/show them by the label when an change is made to the radio button.
$('[type="radio"]').on('change', function () {
$('select')
.val('') // reset value if selection already made
.find('optgroup') // find the groups
.hide() // hide them all
.filter('[label="' + this.value + '"]') // find the one that matches radio
.show() // show it
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="rbDistDiv" border="0">
<tbody><tr>
<td><input id="rbDistDiv_0" type="radio" name="rbDistDiv" value="US"><label for="rbDistDiv_0">US</label></td>
</tr><tr>
<td><input id="rbDistDiv_1" type="radio" name="rbDistDiv" value="UK"><label for="rbDistDiv_1">UK</label></td>
</tr>
</tbody></table>
<br>
<select name="VCSdistSelect$ddlDist" id="VCSdistSelect_ddlDist" class="chosen-select" data-placeholder="Select a Distributor" >
<option selected="selected" value=""></option>
<optgroup label="US">
<option value="123" division="US">Aaron</option>
</optgroup>
<optgroup label="UK">
<option value="655" division="UK">John</option>
</optgroup>
</select>

Related

How can javascript collect values from the same classname in select-option?

I made table for the individual summation of the same classnames as like '30', '60'...
<td>
<select onchange='summation()' class='30' name='Cr'>
<option value=0>>15.0</option>
<option value=1>10.0/15.0</option>
<option value=2><5.0</option>
<option value=3>5.0/10.0</option>
</td>
<td>
<select onchange='summation()' class='30' name='WBC'>
<option value=0><2000</option>
<option value=1>2000~4000</option>
<option value=2> >10000</option>
<option value=3>4000~10000</option>
</td>
<td>
<select onchange='summation()' class='90' name='post-BUN'>
<option value=0>>24</option>
<option value=1><20</option>
<option value=2>20/24</option>
</td>
<td>
<select onchange='summation()' class='180' name='HBsAg'>
<option value=0>posi</option>
<option value=3>nega</option>
</td>
In Browser, that code's displaying below
I made javascript as below. Classname ='30' values are the collection of object.
function summation() {
var x = document.getElementsByClassName("30");
???????????
document.getElementById("30").innerHTML = x.valueOf();
How can I get the summation of the classname="30" from the that code?
When option selected, I want the sum of the values of the classname '30'. In here, 3 and 2 selected, the sum will be 5. I want That sum "5"
I think this is probably what you want, but it's a tiny bit unclear from the requirements. (I'm unsure why you run the "summation" function on the last two selects when you are not including them in the calculation.)
From a code point of view, querySelectorAll is used to find all elements with the same class. The advantage of this vs getElementsByClassName is that you can then easily loop over the items with a forEach as I have done.
Note that I had to alter your class names slightly because JavaScript complains about an invalid selector when the class name starts with a number. But this is a trivial change.
function summation() {
var x = document.querySelectorAll(".select30");
var total = 0;
x.forEach(function(item) {
total += parseInt(item.value);
});
console.log("Total: " + total);
}
<table>
<tr>
<td>
<select onchange='summation()' class='select30' name='Cr'>
<option value=0>>15.0</option>
<option value=1>10.0/15.0</option>
<option value=2><5.0</option>
<option value=3>5.0/10.0</option>
</td>
<td>
<select onchange='summation()' class='select30' name='WBC'>
<option value=0>
<2000</option>
<option value=1>2000~4000</option>
<option value=2> >10000</option>
<option value=3>4000~10000</option>
</td>
<td>
<select onchange='summation()' class='select90' name='post-BUN'>
<option value=0>>24</option>
<option value=1>
<20</option>
<option value=2>20/24</option>
</td>
<td>
<select onchange='summation()' class='select180' name='HBsAg'>
<option value=0>posi</option>
<option value=3>nega</option>
</td>
</tr>
</table>
After agreeing with ADyson and trying to do without a class name and but with data attribute here is what I have done.
const selectItems = document.querySelectorAll("select"); // selecting all select elements
selectItems.forEach(selectItem => { // looping through all select elements
selectItem.addEventListener("change", function() { // calling a function on change
let dataNumber = this.dataset.num;
summation(dataNumber); // passing the value of data-num to find next elements which has same data-num
});
});
function summation(dataNumber) {
const allElements = document.querySelectorAll("[data-num]"); // selecting all elements that has data-num attribute
const allElementsWithSameDataNumber = []; // to store all elements that has same data-num
allElements.forEach(select => {
if (select.dataset.num === dataNumber) {
allElementsWithSameDataNumber.push(select);
}
});
// Calculating the value of same data-number's select elements
let value = 0;
allElementsWithSameDataNumber.forEach(cur => {
value = parseInt(cur.value) + value;
});
console.log(value);
}
<select data-num="30" name="Cr">
<option value="10">10</option>
<option value="1">1</option>
</select>
<select data-num="30" name="WBC">
<option value="3">3</option>
<option value="2"> >2</option>
</select>
<select data-num="180" name="WBC">
<option value="3">3</option>
<option value="2"> >2</option>
</select>
<select data-num="180" name="WBC">
<option value="8">8</option>
<option value="2"> >2</option>
</select>

javascript shows all associated DIVs on a dropdown box select

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>

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>

How do I make all values in html select element selected using Javascript

In Html have two select tags, the first contains all the worlds countries, the second contains only the countries selected by user.
<form action="/fixsongs.fix">
<table>
<tr>
<td colspan="2">
<label title="Potential Releases from these countries get their score boosted">
Preferred Release Countries
</label>
</td>
</tr>
<tr>
<td>
<select id="preferred_countries_all" size="15" style="width:200px" multiple="multiple">
<option value=" AF">Afghanistan</option><option value="AX">Åland Islands</option><option value="AL">Albania</option><option value="DZ">Algeria</option><option value="AS">American Samoa</option><option value="AD">Andorra</option><option value="AO">Angola</option><option value="AI">Anguilla</option><option value="AQ">Antarctica</option><option value="AG">Antigua and Barbuda</option><option value="AR">Argentina</option><option value="AM">Armenia</option><option value="AW">Aruba</option><option value="AU">Australia</option><option value="AT">Austria</option><option value="AZ">Azerbaijan</option><option value="BS">Bahamas</option><option value="BH">Bahrain</option>...<option value="ZW">Zimbabwe</option>
</select>
</td>
<td>
<button style="width:100px" type="button" id="preferred_countries_add" onclick="add_preferred_countries();">
Add
</button>
<br>
<button style="width:100px" type="button" id="preferred_countries_remove" onclick="remove_preferred_countries();">
Remove
</button>
</td>
<td>
<select id="preferred_countries_selected" name="preferred_countries_selected" size="15" style="width:200px" multiple="multiple">
<option value="GB">United Kingdom</option>
</select>
</td>
</tr>
</table>
<input type="submit" value="Start">
The user selects them by highlighting and then click on button which invokes the following Javascript function.
function add_preferred_countries() {
allCountries = document.getElementById('preferred_countries_all');
selectedCountries = document.getElementById('preferred_countries_selected');
var length=$('#preferred_countries_all option:selected').length;
if(length==0) {
return false;
}
$('#preferred_countries_all option:selected').each(function(){
$('#preferred_countries_selected').append($(this));
});
//selectedCountries.value = "";
for (var i = 0; i < selectedCountries.options.length; i++) {
selectedCountries.options[i].selected = selected;
}
}
'
That bits works fine, but I have realized that when I finally submit the form containing this and various other options that it will send items in the select list that are actually selected. So in the absence of a better solution I want to automatically select all values in the preferred_countries_selected whenever user adds new countries, so that when user submits form the preferred countries will be sent to server
I thought this would work, but has no effect
for (var i = 0; i < selectedCountries.options.length; i++) {
selectedCountries.options[i].selected = selected;
I know the existing function has some JQuery in it, but I would prefer pure javascript solution as I don't really understand JQuery syntax.
Ideally I would prefer to do this just as they press submit, but that is another question.
You have some HTML validation issues with your table and you really should not use inline CSS or HTML event attributes (i.e. onclick) as they have many harmful side-effects.
See the inline comments in the code snippet below and note that you need the checked CSS pseudo-class, rather than selected:
// Get references to the two lists
var allCountries = document.getElementById('preferred_countries_all');
var selectedCountries = document.getElementById('preferred_countries_selected');
function add_preferred_countries(operation) {
if(operation === "add"){
// Get the selected countries from list one into an array
var allPreferredSelected = Array.prototype.slice.call(allCountries.querySelectorAll('option:checked'));
// Loop over the array
allPreferredSelected.forEach(function(selOption){
selectedCountries.appendChild(selOption); // Add each to the second list
});
// Loop through the second list and select each option
Array.prototype.slice.call(selectedCountries.querySelectorAll("option")).forEach(function(opt){
opt.selected = "selected";
});
console.log("Item added");
} else {
// Do remove operation here
// Loop over the selected countries in the second list
Array.prototype.slice.call(selectedCountries.querySelectorAll("option:checked")).forEach(function(opt){
selectedCountries.removeChild(opt); // Remove country
});
console.log("Item removed");
}
}
// Get the add and remove buttons into an array and loop over the array
Array.prototype.slice.call(document.querySelectorAll("button[id^='preferred_countries']")).forEach(function(btn){
// Set up a click event handler for the button
btn.addEventListener("click", function(){
add_preferred_countries(this.dataset.action); // Call the add/remove function with the right arg
});
});
/* Do your styling separate from the HTML */
button[id^='preferred_countries'] { width:100px; }
select { width:200px; height:20em; }
<form action="/fixsongs.fix">
<table>
<tr>
<td colspan="2">
<span title="Potential Releases from these countries get their score boosted">
Preferred Release Countries
</span>
</td>
</tr>
<tr>
<td>
<select id="preferred_countries_all" multiple="multiple">
<option value=" AF">Afghanistan</option>
<option value="AX">Åland Islands</option>
<option value="AL">Albania</option>
<option value="DZ">Algeria</option>
<option value="AS">American Samoa</option>
<option value="AD">Andorra</option>
<option value="AO">Angola</option>
<option value="AI">Anguilla</option>
<option value="AQ">Antarctica</option>
<option value="AG">Antigua and Barbuda</option>
<option value="AR">Argentina</option><option value="AM">Armenia</option>
<option value="AW">Aruba</option>
<option value="AU">Australia</option>
<option value="AT">Austria</option>
<option value="AZ">Azerbaijan</option>
<option value="BS">Bahamas</option><option value="BH">Bahrain</option>
...
<option value="ZW">Zimbabwe</option>
</select>
</td>
<td>
<button type="button" id="preferred_countries_add" data-action="add">Add</button>
<br>
<button type="button" id="preferred_countries_remove" data-action="remove">Remove</button>
</td>
<td>
<select id="preferred_countries_selected" name="preferred_countries_selected" multiple="multiple">
<option value="GB">United Kingdom</option>
</select>
</td>
</tr>
</table>
<input type="submit" value="Start">
</form>

Dropdown box - onchange and onselect

I want help, i am very new to html..
On selecting option from dropdown menu, I want html to put the values in word..
e.g. When I select "1" from drop down, it must show "one"
When I select "2' from drop down, it must show "two"
How to do that??
<HTML>
<Table border=10>
<TR>
<TD>Select Number</TD>
<TD><Select>
<option>1</option>
<option>2</option>
<option>3</option>
</Select></TD>
</TR>
<tr>
<td>In Words</td>
<td><input type="text" readonly></td>
</tr>
</Table>
</HTML>
Please make a script and show me...
A non-jQuery solution:
Firstly, give your select- and input-tags id's, and your options values (value=""). Then add a onchange=""-listener in the select-tag and make a function that carries out what you want to do (i.e. checking the selected value and displaying it in your input field), like so:
function showValue() {
var x = document.getElementById("mySelect").value;
document.getElementById("mySelection").value = "You selected: " + x;
}
<Table border=10>
<tr>
<td>Select Number</td>
<td><Select onchange="showValue()" id="mySelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</Select></td>
</tr>
<tr>
<td>In Words</td>
<td><input type="text" id="mySelection"></td>
</tr>
</Table>
If I understand what you want, you'll need some javascript to find what you selected, and take that 'string' and shove it in an element for the user to see.
Here is a working example. Try making one these next time you ask a question. Welcome to Stack Overflow.
http://jsfiddle.net/sheriffderek/6vp5Lskn/
HTML
<select name='my_select' id='my_select'>
<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>
<div id="outcome">
You have selected: <span></span>
</div>
javascript (jQuery)
var selectedOption; // define this variable
// when the select is changed...
$('#my_select').on('change', function() {
// get the option that was selected
selectedOption = $( "#my_select option:selected" ).text();
// put the option in the place you want it
$('#outcome span').html(selectedOption);
});

Categories