How to add an option to a dropdown menu created by JavaScript - javascript

Hi I am 15 and just starting to learn HTML CSS and JavaScript.
I am trying to edit a drop down menu for listing all 50 states on a checkout page, by default it is blank when the page loads and i want it to say "State". I am trying to make one more option that says "State" with a attribute of selected and disabled. I have no clue on how to do this because it is all JavaScript and i have looked online and have found nothing.
So i need some help on how to do this, i have no idea how to do it in JavaScript
I didn't write any of this code and i don't know what most of it even does, that is why i gave you the whole document, i am just trying to edit it.
Here is the JavaScript/PHP i am trying to edit.
// If you have PHP you can set the post values like this
//var postState = '<?= $_POST["state"] ?>';
//var postCountry = '<?= $_POST["country"] ?>';
var postState = 'US';
var postCountry = 'FL';
// State table
//
// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var stateList = '\
US:AL:Alabama|\
US:AK:Alaska|\
CA:AB:Alberta|\
US:AZ:Arizona|\
US:AR:Arkansas|\
CA:BC:British Columbia|\
US:CA:California|\
US:CO:Colorado|\
US:CT:Connecticut|\
US:DE:Delaware|\
US:DC:District of Columbia|\
US:FL:Florida|\
US:GA:Georgia|\
US:HI:Hawaii|\
US:ID:Idaho|\
US:IL:Illinois|\
US:IN:Indiana|\
US:IA:Iowa|\
US:KS:Kansas|\
US:KY:Kentucky|\
US:LA:Louisiana|\
US:ME:Maine|\
CA:MB:Manitoba|\
US:MD:Maryland|\
US:MA:Massachusetts|\
US:MI:Michigan|\
US:MN:Minnesota|\
US:MS:Mississippi|\
US:MO:Missouri|\
US:MT:Montana|\
US:NE:Nebraska|\
US:NV:Nevada|\
CA:NB:New Brunswick|\
US:NH:New Hampshire|\
US:NJ:New Jersey|\
US:NM:New Mexico|\
US:NY:New York|\
CA:NL:Newfoundland and Labrador|\
US:NC:North Carolina|\
US:ND:North Dakota|\
CA:NT:Northwest Territories|\
CA:NS:Nova Scotia|\
CA:NU:Nunavut|\
US:OH:Ohio|\
US:OK:Oklahoma|\
CA:ON:Ontario|\
US:OR:Oregon|\
US:PA:Pennsylvania|\
CA:PE:Prince Edward Island|\
US:PR:Puerto Rico|\
CA:QC:Quebec|\
US:RI:Rhode Island|\
CA:SK:Saskatchewan|\
US:SC:South Carolina|\
US:SD:South Dakota|\
US:TN:Tennessee|\
US:TX:Texas|\
US:UT:Utah|\
US:VT:Vermont|\
US:VI:Virgin Islands|\
US:VA:Virginia|\
US:WA:Washington|\
US:WV:West Virginia|\
US:WI:Wisconsin|\
US:WY:Wyoming|\
CA:YT:Yukon Territory|\
';
// Country data table
//
// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var country = '\
AF:Afghanistan|\
AX:Aland Islands|\
AL:Albania|\
DZ:Algeria|\
AS:American Samoa|\
AD:Andorra|\
AO:Angola|\
AI:Anguilla|\
AQ:Antarctica|\
AG:Antigua & Barbuda|\
AR:Argentina|\
AM:Armenia|\
AW:Aruba|\
AU:Australia|\
AT:Austria|\
AZ:Azerbaijan|\
AP:Azores|\
BS:Bahamas|\
BH:Bahrain|\
BD:Bangladesh|\
BB:Barbados|\
BY:Belarus|\
BE:Belgium|\
BZ:Belize|\
BJ:Benin|\
BM:Bermuda|\
BT:Bhutan|\
BO:Bolivia|\
BL:Bonaire|\
BA:Bosnia|\
BW:Botswana|\
BV:Bouvet Island|\
BR:Brazil|\
VG:British Virgin Islands|\
BN:Brunei|\
BG:Bulgaria|\
BF:Burkina Faso|\
BI:Burundi|\
KH:Cambodia|\
CM:Cameroon|\
CA:Canada|\
IC:Canary Islands|\
CV:Cape Verde Islands|\
KY:Cayman Islands|\
CF:Central African Republic|\
TD:Chad|\
CD:Channel Islands|\
CL:Chile|\
CN:China|\
CX:Christmas Island|\
CC:Cocos (keeling) Islands|\
CO:Colombia|\
CG:Congo|\
CK:Cook Islands|\
CR:Costa Rica|\
CI:Cote Divoire|\
HR:Croatia|\
CB:Curacao|\
CY:Cyprus|\
CZ:Czech Republic|\
DK:Denmark|\
DJ:Djibouti|\
DM:Dominica|\
DO:Dominican Republic|\
EC:Ecuador|\
EG:Egypt|\
SV:El Salvador|\
EN:England|\
GQ:Equitorial Guinea|\
ER:Eritrea|\
EE:Estonia|\
ET:Ethiopia|\
FO:Faeroe Islands|\
FK:Falkland Islands (Malvinas)|\
FJ:Fiji|\
FI:Finland|\
FR:France|\
GF:French Guiana|\
PF:French Polynesia|\
TF:French Southern Territories|\
GA:Gabon|\
GM:Gambia|\
GE:Georgia|\
DE:Germany|\
GH:Ghana|\
GI:Gibraltar|\
GR:Greece|\
GL:Greenland|\
GD:Grenada|\
GP:Guadeloupe|\
GU:Guam|\
GT:Guatemala|\
GG:Guernsey|\
GN:Guinea|\
GW:Guinea-Bissau|\
GY:Guyana|\
HT:Haiti|\
HM:Heard Island and Mcdonald Islands|\
HO:Holland|\
VA:Holy See (Vatican City State)|\
HN:Honduras|\
HK:Hong Kong|\
HU:Hungary|\
IS:Iceland|\
IN:India|\
ID:Indonesia|\
IR:Iran|\
IQ:Iraq|\
IE:Ireland|\
IM:Isle of Man|\
IL:Israel|\
IT:Italy|\
JM:Jamaica|\
JP:Japan|\
JE:Jersey|\
JO:Jordan|\
KZ:Kazakhstan|\
KE:Kenya|\
KI:Kiribati|\
KP:Korea, Democratic People\'s Republic of|\
KR:Korea, Republic of|\
KO:Kosrae|\
KW:Kuwait|\
KG:Kyrgyzstan|\
LA:Laos|\
LV:Latvia|\
LB:Lebanon|\
LS:Lesotho|\
LR:Liberia|\
LY:Libyan Arab Jamahiriya|\
LI:Liechtenstein|\
LT:Lithuania|\
LU:Luxembourg|\
MO:Macau|\
MK:Macedonia, Republic of|\
MG:Madagascar|\
MW:Malawi|\
MY:Malaysia|\
MV:Maldives|\
ML:Mali|\
MT:Malta|\
MH:Marshall Islands|\
MQ:Martinique|\
MR:Mauritania|\
MU:Mauritius|\
YT:Mayotte|\
MX:Mexico|\
FM:Micronesia, Federated States of|\
MD:Moldova|\
MC:Monaco|\
MN:Mongolia|\
ME:Montenegro, Republic of|\
MS:Montserrat|\
MA:Morocco|\
MZ:Mozambique|\
MM:Myanmar|\
NA:Namibia|\
NR:Nauru|\
NP:Nepal|\
NL:Netherlands|\
AN:Netherlands Antilles|\
NC:New Caledonia|\
NZ:New Zealand|\
NI:Nicaragua|\
NE:Niger|\
NG:Nigeria|\
NU:Niue|\
NF:Norfolk Island|\
NB:Northern Ireland|\
MP:Northern Mariana Islands|\
NO:Norway|\
OM:Oman|\
PK:Pakistan|\
PW:Palau|\
PS:Palestinian Territory, Occupied|\
PA:Panama|\
PG:Papua New Guinea|\
PY:Paraguay|\
PE:Peru|\
PH:Philippines|\
PN:Pitcairn Island|\
PL:Poland|\
PO:Ponape|\
PT:Portugal|\
PR:Puerto Rico|\
QA:Qatar|\
RE:Reunion|\
RO:Romania|\
RT:Rota|\
RU:Russia|\
RW:Rwanda|\
SS:Saba|\
SP:Saipan|\
SM:San Marino|\
ST:Sao Tome and Principe|\
SA:Saudi Arabia|\
SF:Scotland|\
SN:Senegal|\
RS:Serbia, Republic of|\
SC:Seychelles|\
SL:Sierra Leone|\
SG:Singapore|\
SK:Slovakia|\
SI:Slovenia|\
SB:Solomon Islands|\
SO:Somalia|\
ZA:South Africa|\
ES:Spain|\
LK:Sri Lanka|\
NT:St. Barthelemy|\
SW:St. Christopher|\
SX:St. Croix|\
EU:St. Eustatius|\
UV:St. John|\
KN:St. Kitts & Nevis|\
LC:St. Lucia|\
MB:St. Maarten|\
TB:St. Martin|\
VL:St. Thomas|\
VC:St. Vincent & the Grenadines|\
SD:Sudan|\
SR:Suriname|\
SZ:Swaziland|\
SE:Sweden|\
CH:Switzerland|\
SY:Syrian Arab Republic|\
TA:Tahiti|\
TW:Taiwan|\
TJ:Tajikistan|\
TZ:Tanzania|\
TH:Thailand|\
TL:Timor-Leste|\
TI:Tinian|\
TG:Togo|\
TO:Tonga|\
TT:Trinidad and Tobago|\
TU:Truk|\
TN:Tunisia|\
TR:Turkey|\
TM:Turkmenistan|\
TC:Turks & Caicos Islands|\
TV:Tuvalu|\
UG:Uganda|\
UA:Ukraine|\
UI:Union Island|\
AE:United Arab Emirates|\
GB:United Kingdom|\
US:United States|\
UY:Uruguay|\
VI:US Virgin Islands|\
UZ:Uzbekistan|\
VU:Vanuatu|\
VE:Venezuela|\
VN:Vietnam|\
VR:Virgin Gorda|\
WK:Wake Island|\
WL:Wales|\
WF:Wallis and Futuna|\
EH:Western Sahara|\
WS:Western Samoa|\
YA:Yap|\
YE:Yemen|\
ZR:Zaire|\
ZM:Zambia|\
ZW:Zimbabwe|\
';
country = country.substring(0, country.length-1) // Deleting the last "|" character
function get_Element(i)
{
return document.getElementById(i) || document.getElementsByName(i).item(0);
}
function TrimString(sInString) {
if ( sInString ) {
sInString = sInString.replace( /^\s+/g, "" );// strip leading
return sInString.replace( /\s+$/g, "" );// strip trailing
}
}
// Populates the country selected with the counties from the country list
function populateCountry(defaultCountry,countryfieldname) {
if (defaultCountry=="") {defaultCountry="US"}
var countryLineArray = country.split('|'); // Split into lines
var selObj = get_Element(countryfieldname);
if (!selObj) return;
selObj.options[0] = new Option('','');
selObj.selectedIndex = 0;
for (var loop = 0; loop < countryLineArray.length; loop++) {
lineArray = countryLineArray[loop].split(':');
countryCode = TrimString(lineArray[0]);
countryName = TrimString(lineArray[1]);
if ( countryCode != '' ) { selObj.options[loop] = new Option(countryName, countryCode); }
if ( defaultCountry == countryCode ) { selObj.selectedIndex = loop; }
}
}
function populateState(statefieldname,countryfieldname,state1,optionalCreateTextField) {
//optionalCreateTextField = optional parameter, true/false. When a country doesn't have state, it'll determine if the code creates a text field for the state or just let the dropdown empty.
var isOpera = false, isIE = false;
var strClassName;
var originalTabIndex;
if(typeof(window.opera) != 'undefined')
{isOpera = true;}
if(!isOpera && (navigator.userAgent.indexOf('Internet Explorer') > 0 || navigator.userAgent.indexOf('MSIE') > 0) && navigator.userAgent.indexOf('MSIE 9') < 0 && navigator.userAgent.indexOf('MSIE 10') < 0)
{isIE = true;}
if (state1==undefined) {state1='';}
postCountry=get_Element(countryfieldname);
if (!postCountry) return;
postCountry=postCountry.value;
var selObj = get_Element(statefieldname);
if (!selObj) return;
var foundState = false;
originalTabIndex = selObj.getAttribute("tabindex");
// Empty options just in case new drop down is shorter
if ( selObj.type == 'select-one' ) {
selObj.options.length = 0;
// selObj.options[0] = new Option('Select State','');
// selObj.selectedIndex = 0;
}
// Populate the drop down with states from the selected country
//
var stateLineArray = stateList.split("|"); // Split into lines
var optionCntr = 0;
for (var loop = 0; loop < stateLineArray.length; loop++) {
lineArray = stateLineArray[loop].split(":");
countryCode = TrimString(lineArray[0]);
stateCode = TrimString(lineArray[1]);
stateName = TrimString(lineArray[2]);
if ( get_Element(countryfieldname).value == countryCode && countryCode != '' ) {
// If it's a input element, change it to a select
//
if ( selObj.type == 'text' ) {
strClassName = selObj.className;
parentObj = get_Element(statefieldname).parentNode;
// Create the Input Field
if(!isIE){
var inputSel = document.createElement("SELECT");
inputSel.setAttribute("name", statefieldname);
if (strClassName != 'undefined' && strClassName != '')
inputSel.setAttribute("class",strClassName);
else
inputSel.setAttribute("class","txtBoxStyle");
inputSel.setAttribute("id", statefieldname);
}
else
{
var inputSel = document.createElement("<select name="+statefieldname+" id="+statefieldname+">");
if (strClassName != 'undefined' && strClassName != '')
inputSel.setAttribute("className",strClassName);
else
inputSel.setAttribute("className","txtBoxStyle");
}
inputSel.setAttribute("tabindex", originalTabIndex);
parentObj.insertBefore(inputSel, selObj.nextSibling);
parentObj.removeChild(selObj);
selObj = get_Element(statefieldname);
}
if (optionCntr==0)
{
selObj.options[optionCntr] = new Option('','');
selObj.selectedIndex = optionCntr;
optionCntr++;
}
if ( stateCode != '' ) {
selObj.options[optionCntr] = new Option(stateName, stateCode);
}
// See if it's selected from a previous post
//
if ( stateCode == state1 && countryCode == postCountry ) {
selObj.selectedIndex = optionCntr;
}
foundState = true;
optionCntr++
}
}
// If the country has no states, change the select to a text box
//
if ( ! foundState ) {
if (postCountry == 'ALL')
{
//var selObj = get_Element(statefieldname);
selObj.options.length = 0;
selObj.options[0] = new Option('ALL','ALL');
selObj.selectedIndex = 0;
}
else
{
if (optionalCreateTextField == undefined)
var createText = true;
else
var createText = optionalCreateTextField;
if (createText)
{
strClassName = selObj.className;
parentObj = get_Element(statefieldname).parentNode;
// Create the Input Field
if(!isIE){
var inputEl = document.createElement("input");
inputEl.setAttribute("name", statefieldname);
if (strClassName != 'undefined' && strClassName != '')
inputEl.setAttribute("class",strClassName);
else
inputEl.setAttribute("class","txtBoxStyle");
inputEl.setAttribute("id", statefieldname);
}
else
{
var inputEl = document.createElement("<input name=\""+statefieldname+"\" id=\""+statefieldname+"\" />");
if (strClassName != 'undefined' && strClassName != '')
inputEl.setAttribute("className",strClassName);
else
inputEl.setAttribute("className","txtBoxStyle");
}
inputEl.setAttribute("tabindex", originalTabIndex);
inputEl.setAttribute("type", "text");
inputEl.setAttribute("size", 20);
inputEl.setAttribute("value", state1);
parentObj.insertBefore(inputEl, selObj.nextSibling);
parentObj.removeChild(selObj);
}
}
}
}
function insertCountry(strCountryName,countryfieldname) {
var selObj = get_Element(countryfieldname);
if (!selObj) return;
selObj.options[selObj.options.length] = new Option('ALL','ALL');
selObj.selectedIndex = selObj.options.length-1;
}
function initCountry(country,state1,statefieldname,countryfieldname) {
populateCountry(country,countryfieldname);
populateState(statefieldname,countryfieldname,state1);
}
function GetValue(formx,name1) {
//alert(name1);
var i;
for(i=0;i<formx.elements.length;i++) {
if(formx.elements[i].name==name1) {
return formx.elements[i].value;
}
}
}
And Here is the HTML
<div class="chkField">
<label for="billing_state">[CustomerInfo_state]</label>
<select id="billing_state" onchange="this.form.billing_zip.value='';check_address('billing');" name="billing_state" tabindex="9" class="txtBoxStyle">
</select>
I don't know how to edit JavaScript very well but it seems to be creating HTML options on the web page and i dont know how to create another one that says "States", any help would be much appreciated.
Thanks,
Andrew

try to use append() function of jquery
like if your html is like
<html>
<select id="temp"></select>
</html>
$("#temp").append("<option>Your Value</option>")

Related

Dropdown selection value doesn't become a real value and work in JavaScript

I have a language dropdown and I try to alert the user to have to choose one language before doing anything further like languageOption can become a string and go into array. But it's not working and I don't understand why. I tried:
alert("You didn't choose any language.");
console.alert("You didn't choose any language.");
console.log("You didn't choose any language.");
But they all don't work.
And I thought another way to solve this, which I make
<option value="1" selected>English (American)</option>
but then the value = "1" doesn't become the a value for variable 'languageOption'. So the arrays don't respond and don't know what to do when I see in console. I don't understand why the array is not responding.
Any help I would appreciate.
Below is my code:
<select id="languageSelection" style=display:none>
<option value="">Choose a language</option>
<option value="1">English (American)</option>
<option value="2">Chinese (Mandarin)</option>
<option value="3">Japanese</option>
</select>
var audioSrc = "sound/"
var audioType = ".wav";
// default number of random question, if user this used the dropdown
var default_numFollowUp = 4;
// default delai (seconds) between random questions, if user this used the dropdown
var default_secFollowUp = 10;
// Create the audio element
var audioElement = document.createElement('audio');
var endingArr = [];
var runThroughArr = [];
var randomArr = [];
var languageOption = parseInt($("#languageSelection").val() );
$("#languageSelection").on("change", function(){
languageOption = $(this).val(); // Make languageOption value be string
//if(languageOption.length==0){languageOption=1;}
console.log("langugeOption is " + languageOption);
console.log("Language changed to: "+ $(this).find("option").eq( $(this)[0].selectedIndex ).text() + " (Index: "+languageOption+")" );
console.log(typeof(languageOption)); // Outputs string
endingArr = [];
runThroughArr = [];
randomArr = [];
if(languageOption === ""){
alert("You didn't choose any language.");
console.alert("You didn't choose any language.");
console.log("You didn't choose any language.");
}
else if(languageOption === "1"){
console.log("English");
for(i = 0; i < intro_playList.length; i++){
if(intro_playList[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList[i].runThrough){ runThroughArr.push(i); }
if(intro_playList[i].random){ randomArr.push(i); }
}
}
else if (languageOption === "2"){
console.log("Chinese");
for(i = 0; i < intro_playList_chi.length; i++){
if(intro_playList_chi[i].stage === "ending"){ endingArr.push(i); }
if(intro_playList_chi[i].runThrough){ runThroughArr.push(i); }
if(intro_playList_chi[i].random){ randomArr.push(i); }
}
}
});
You need to assign the onchange function after loading the document. With jQuery, you can do it like this
var languageOption;
$(document).on("ready", function() {
languageOption = $("#languageSelection").val();
$("#languageSelection").on("change", function() {
your code here ...
}
}

Disable select option based on innerhtml with pure JavaScript

Scenario: User votes via HTML form for a field trip to take on a bus. There are three options:
<select id="selectbox">
<option>Berlin</option>
<option>Munich</option>
<option>Cologne</option>
</select>
The free bus seats are stored in / read from a database: ($tour is our array keeping the free seats)
<table class="status">
<tr><td>Berlin: <span id="t1">available (<?php echo $tour[0]; ?> seats)</span></td></tr>
<tr><td>Munich: <span id="t2">available (<?php echo $tour[1]; ?> seats)</span></td></tr>
<tr><td>Cologne: <span id="t3">available (<?php echo $tour[2]; ?> seats)</span></td></tr>
</table>
If free seats are zero, we display a "sorry, booked out" info using vanilla JavaScript:
// get content of status table
var t1 = document.getElementById("t1").innerHTML;
var t2 = document.getElementById("t2").innerHTML;
var t3 = document.getElementById("t3").innerHTML;
var bookedout = "sorry, booked out!"
// check if condition is met
if (t1 == "available (0 seats)") {
document.getElementById("t1").innerHTML = bookedout;
}
if (t2 == "available (0 seats)") {
document.getElementById("t2").innerHTML = bookedout ;
}
if (t3 == "available (0 seats)") {
document.getElementById("t3").innerHTML = bookedout ;
}
Works fine. However, now comes the part I'm a bit lost. The above condition should also delete the respective option from #selectbox based on the option's innerHTML. In jQuery I'd go with something like #selectbox option:contains('stringhere').
However, I wanna do it in the purest of JavaScript. Any ideas?
It's fairly straight forward..
First in your html give vlaues to your options:
<select id="selectbox">
<option>Berlin</option>
<option>Munich</option>
<option>Cologne</option>
</select>
Then in js:
var mySelect = document.getElementById("selectbox");
//function to get option values as array
function getOptionsArr() {
var optionsArray =[],options = mySelect.options;
var i = 0, len = options.length;
// store the options value in an array
while (i < len)
{
optionsArray.push(options[i++].value);
}
return optionsArray;
}
var t1 = document.getElementById("t1").innerHTML;
var t2 = document.getElementById("t2").innerHTML;
var t3 = document.getElementById("t3").innerHTML;
var bookedout = "sorry, booked out!"
// check if condition is met
if (t1 == "available (0 seats)"){
document.getElementById("t1").innerHTML = bookedout;
//this will get the whole parent node and child node inner text we split at : and get the value
var textArr = document.getElementById("t1").parentElement.innerText.split(':');
// find the index of value from our array created above and remove that option from select
mySelect.remove(getOptionsArr().indexOf(textArr [0]))
}
//repeat the same for other
if (t2 == "available (0 seats)"){
document.getElementById("t2").innerHTML = bookedout ;
var textArr = document.getElementById("t2").parentElement.innerText.split(':');
mySelect.remove(getOptionsArr().indexOf(textArr [0]))
}
if (t3 == "available (0 seats)"){
document.getElementById("t3").innerHTML = bookedout ;
var textArr = document.getElementById("t3").parentElement.innerText.split(':');
mySelect.remove(getOptionsArr().indexOf(textArr [0]))
}
Aditionally you can refactor it by
var mySelect = document.getElementById("selectbox");
//function to get option values as array
function getOptionsArr() {
var optionsArray =[],options = mySelect.options;
var i = 0, len = options.length;
// store the options value in an array
while (i < len)
{
optionsArray.push(options[i++].value);
}
return optionsArray;
}
var t1 = document.getElementById("t1").innerHTML;
var t2 = document.getElementById("t2").innerHTML;
var t3 = document.getElementById("t3").innerHTML;
var bookedout = "sorry, booked out!"
// check if condition is met
if (t1 == "available (0 seats)"){
doUpdateDOM("t1")
}
if (t2 == "available (0 seats)"){
doUpdateDOM("t2")
}
if (t3 == "available (0 seats)"){
doUpdateDOM("t3")
}
function doUpdateDOM(nodeID){
document.getElementById(nodeID).innerHTML = bookedout;
var textArr = document.getElementById(nodeID).parentElement.innerText.split(':');
mySelect.remove(optionsArray.indexOf(textArr [0]))
}
Assuming that the order of the options inside the select correspond to the order inside the table element you could simply do something like this.
var select = document.getElementById('selectbox');
var table = document.getElementsByClassName('status').item(0);
var rows = table.rows;
var bookedout = " sorry, booked out!";
// check whether an option is bookedout
// and save its state to a new array.
var bookedOutState = [].slice.call(rows).map(function(row) {
var match = row.children[0].textContent.match(/\d/);
if (+match[0] === 0) {
row.children[0].textContent = match['input'].substr(0, match['input'].indexOf(':') + 1) + bookedout;
return false;
}
return true;
})
// go over the new created array and remove
// options from select according to the saved state.
bookedOutState.forEach(function(state, idx) {
if (!state) {
select.removeChild(select.children[idx])
}
})
<select id="selectbox">
<option>Berlin</option>
<option>Munich</option>
<option>Cologne</option>
</select>
<table class="status">
<tr><td>Berlin: <span id="t1">available 0 seats</span></td></tr>
<tr><td>Munich: <span id="t2">available 1 seats</span></td></tr>
<tr><td>Cologne: <span id="t3">available 2 seats</span></td></tr>
</table>

How can I populate dropdown values dynamically based on prior selection?

I have 3 dropdowns with some values. I am using JavaScript to pre-populate the first dropdown.
Based on the selected value in 1st dropdown, how can I populate values in the rest 2 dropdowns (using pure javascript)?
I am framing a URL based on the user selected values in 3 dropdowns using function getURL ,but unable to capture the prepopluated product Name in the URL. Why is it showing the value of ProductName as undefined?
Javascript:
<script>
var ProductNameMap = {
"ProductA":[{"version":"1.0.0","fileName":"FileA1.zip","fileName":"FileA11.dmg"},{"version":"1.0.1","fileName":"FileA2.zip","fileName":"FileA22.dmg"}],
"ProductB":[{"version":"3.5.0","fileName":"FileB1.zip","fileName":"FileB11.dmg"},{"version":"4.0.1","fileName":"FileB2.zip","fileName":"FileB21.dmg"}],
"ProductC":[{"version":"1.0.0","fileName":"FileC1.zip","fileName":"FileC11.dmg"},{"version":"1.0.1","fileName":"FileC2.zip","fileName":"FileC21.dmg"}]
};
function PrepopulateProductName()
{
var ProductNameselect = document.getElementById('selProductName');
var i=1;
for (selProductName in ProductNameMap){
ProductNameselect.options[i++] = new Option(selProductName)
}
}
function changeProductName(productNameID)
{
//Need to populate version dropdown of selected Product
}
function changeProductVersion(productVersionID)
{
//Need to populate file name dropdown of selected ProductVersion
}
function getURL() {
var url = "http://abc.def.com";
var pnid = (selProductName == "") ? "0" : selProductName.value;
var psid = (selProductVersion.value == "") ? "0" : selProductVersion.value;
var pfid = (selFileName.value == "") ? "0" : selFileName.value;
url += "/" + pnid;
url += "/" + psid;
url += "/" + pfid;
document.getElementById("text").innerHTML = "Download Link : ";
document.getElementById("myAnchor").innerHTML = url;
document.getElementById("myAnchor").href = url;
document.getElementById("myAnchor").target = "_blank";
}
</script>
HTML:
Product Name:
<select id="selProductVersion" name="selProductVersion"
onchange="changeProductName(this.value);">
<option>--Choose Product Name--</option>
</select>
Product Version:
<select id="selProductVersion" name="selProductVersion"
onchange="changeProductVersion(this.value);">
</select>
File Name:
<select id="selFileName" name="selFileName"></select>
<button onclick="getURL()">Get URL</button>
<p id="text"></p>
<a id="myAnchor"></a>
Loop through the array of details for the product name to get the versions.
The filename property should be an array so you can have multiple files for each version.
var ProductNameMap = {
"ProductA": [{"version": "1.0.0", "fileName": ["FileA1.zip", "FileA11.zip"]}, {"version": "1.0.1", "fileName": ["FileA2.zip", "FileA22.zip"]}],
"ProductB": [{"version": "3.5.0", "fileName": ["FileB1.zip", "FileB11.zip"]}, {"version": "4.0.1", "fileName": ["FileB2.zip", "FileB22.zip"]}],
"ProductC": [{"version": "1.0.0", "fileName": ["FileC1.zip", "FileC11.zip"]}, {"version": "1.0.1", "fileName": ["FileC2.zip", "FileC22.zip"]}]
};
function PrepopulateProductName() {
var ProductNameselect = document.getElementById('selProductName');
var i = 1;
for (var selProductName in ProductNameMap) {
ProductNameselect.options[i++] = new Option(selProductName)
}
}
function changeProductName(productNameID) {
var versionSelect = document.getElementById('selProductVersion');
versionSelect.innerHTML = '<option>--Choose Product Version</option>'; // Remove previous options
var fileSelect = document.getElementById('selFileName');
fileSelect.innerHTML = '<option>--Choose Filename</option>'; // Remove previous options
var versions = ProductNameMap[productNameID];
for (var i = 0; i < versions.length; i++) {
versionSelect.appendChild(new Option(versions[i].version));
}
}
function changeProductVersion(productVersion) {
var productNameID = document.getElementById('selProductName').value;
var fileSelect = document.getElementById('selFileName');
fileSelect.innerHTML = ''; // Remove previous options
var versions = ProductNameMap[productNameID];
for (var i = 0; i < versions.length; i++) {
if (versions[i].version == productVersion) {
var filenames = versions[i].fileName;
for (var j = 0; j < filenames.length; j++) {
fileSelect.appendChild(new Option(filenames[j]));
}
break;
}
}
}
PrepopulateProductName();
Product Name:
<select id="selProductName" name="selProductName" onchange="changeProductName(this.value);">
<option>--Choose Product Name--</option>
</select>
<br>Product Version:
<select id="selProductVersion" name="selProductVersion" onchange="changeProductVersion(this.value);">
</select>
<br>File Name:
<select id="selFileName" name="selFileName"></select>

Javascript won't change page content

Had this code running fine when I was using a javascript window prompt to input the length. I have now changed it to use an if statement and a dropdown window in the html, and it does not seem to work? Been trying to figure out where the problem is for a few hours, so would be really grateful if someone could point me in the right direction!
HTML:
<select name="paraSize" id ="paraSize">
<option value="small">Small</option>
<option value="medium">Medium</option>
<option value="large">Large</option>
</select>
JavaScript:
var getRekt = function() {
var ipsumLength = 0
var numberParagraph = document.getElementById("paragraphs").value;
var paragraphSize = document.getElementById("paraSize").value;
var startRektIpsum = document.getElementById("startRekt").checked;
if (paragraphSize === small) {
(ipsumLength = 9);
};
else if (paragraphSize === medium) {
(ipsumLength = 25);
};
else if (paragraphSize === large) {
(ipsumLength= 38);
};
var string = "Rekt Ipsum ";
var rektIpsum = [
//Array of words which I won't bore you with
];
for (i = 0; i <= ipsumLength; i++) {
(string = (string + " " + rektIpsum[Math.floor((Math.random() * (rektIpsum.length)) )]))
}
document.getElementById("p1").innerHTML = (string);
}
As noted in my comments the problems was syntactical... but the solution can be simplified to
var paragraphSizeMap = {
small: 9,
medium: 25,
large: 38
}
var getRekt = function () {
var numberParagraph = document.getElementById("paragraphs").value;
var paragraphSize = document.getElementById("paraSize").value;
var startRektIpsum = document.getElementById("startRekt").checked;
var ipsumLength = paragraphSizeMap[paragraphSize] || 0;
var string = "Rekt Ipsum ";
var rektIpsum = ['', '', ''];
for (i = 0; i < ipsumLength; i++) {
string += " " + rektIpsum[Math.floor(Math.random() * rektIpsum.length)]
}
document.getElementById("p1").innerHTML = string;
}

Drop down box text disappears after completing a function, how can I get it to display what option was chosen?

The functions below work fine, the only thing I need help with is that when I pick an option from a drop down menu, it runs the function, but it erases all of the options in the drop down box. How can I get it NOT to do that and continue displaying my original options in the same drop down box?
<script type="text/javascript">
function gbid(s) {
return document.getElementById(s);
}
function myCount() {
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open("somefilepathhere.xlsx");
var excel_sheet = excel.Worksheets("Sheet1");
var agent,count
agent=document.getElementById("tAgent").value;
if (agent=="Agent1")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(1,1).Value;
}
else if (agent=="Agent2")
{
count=gbid('tAgent').innerText = excel_sheet.Cells(2,1).Value;
}
document.getElementById("disphere").innerHTML = count;
excel.Quit();
excel.Application.Quit();
}
function saveToExcel() {
var myApp = new ActiveXObject("Excel.Application");
myApp.visible = false;
var xlCellTypeLastCell = 11;
var x = document.forms["f1"]["tAgent"].value;
if (x == null || x == "") {
alert("You must select an 'Entered By' option!");
return false;
}
else
var myWorkbook = myApp.Workbooks.Open(filePath);
var myWorksheet = myWorkbook.Worksheets(1);
myWorksheet.Activate;
objRange = myWorksheet.UsedRange;
objRange.SpecialCells(xlCellTypeLastCell).Activate;
newRow = myApp.ActiveCell.Row + 1;
alert('A new log was created on row '+newRow);
strNewCell = "A" + newRow;
myApp.Range(strNewCell).Activate;
myWorksheet.Cells(newRow,1).value = f1.tMemberid.value;
myWorksheet.Cells(newRow,2).value = f1.tDate.value;
myWorksheet.Cells(newRow,3).value = f1.tRep.value;
myWorksheet.Cells(newRow,4).value = f1.tIssuerep.value;
myWorksheet.Cells(newRow,5).value = f1.tLOB.value;
myWorksheet.Cells(newRow,6).value = f1.tContactnum.value;
myWorksheet.Cells(newRow,7).value = f1.tMembername.value;
myWorksheet.Cells(newRow,8).value = f1.tIssid.value;
myWorksheet.Cells(newRow,9).value = f1.tTypeofissue.value;
myWorksheet.Cells(newRow,10).value = f1.tDiscofissue.value;
myWorksheet.Cells(newRow,11).value = f1.tTimesent.value;
myWorksheet.Cells(newRow,12).value = f1.tSendto.value;
myWorksheet.Cells(newRow,13).value = f1.tAgent.value;
myWorkbook.Close(true);
myApp.Workbooks.Close;
myApp.Close;
alert('Process Complete!');
}
</script>
<table >
<tr>
<td class="tb_bor" Align="center" ><h1>ACA Issues Tracker</h1><br />
<b>Entered By: </b>
<select name="tAgent" id="tAgent" style="80% !important;" onchange="myCount()">
<option value="" ></option>
<option value="Agent1" >Agent 1</option>
<option value="Agent2" >Agent 2</option>
</select>
<br />You have completed: <p id="disphere"></p>
<hr>
</td>
</tr>
</table>
With the below line you overwrite the inner text of your select field:
count = gbid( 'tAgent' ).innerText = excel_sheet.Cells( 1,1 ).Value;
^
|
Allthough I'm not clear on what you desire to achieve with the code because I don't understand your usecase, I think you might have mistaken the second equals sign with a string concatenation or something?
This might be what you tried to achieve:
count = gbid( 'tAgent' ).innerText + ' ' + excel_sheet.Cells( 1,1 ).Value;
This is a corrected version of your function:
function myCount() {
var excel = new ActiveXObject( 'Excel.Application' ),
excel_file = excel.Workbooks.Open( 'somefilepathhere.xlsx' ),
excel_sheet = excel.Worksheets( 'Sheet1' ),
agent = document.getElementById( 'tAgent' ).value,
count;
if ( agent === 'Agent1' ) {
count = excel_sheet.Cells( 1,1 ).Value;
} else if ( agent === 'Agent2' ) {
count = excel_sheet.Cells( 2,1 ).Value;
}
document.getElementById( 'disphere' ).innerHTML = count;
excel.Quit();
excel.Application.Quit();
}

Categories

Resources