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

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>

Related

Get Elements of a HTML div

i am building a configuration utility and having a problem with the js.
I am very new to javascript so i apologize in advance for the request for help.
in my HTML i have multiple divs that are structured like this:
<div id="options" class="opt">
<h2 id="optionName">Power Button Options</h2>
<label for="pwrAvl">Power Button Available</label>
<input type="checkbox" name="pwrAvl" id="pwrAvl"/ >
<br /><br />
<label for="pwrLabel">Power Button Label</label>
<input type="text" name="pwrLabel" id="pwrLabel"/ >
<br /><br />
<label for="pwrGraphic">Power Button Graphic</label>
<select name="pwrGraphic" id="pwrGraphic">
<option value="" selected>
----- Please select a graphic -----
</option>
<option value="power.jpeg">Power</option>
<option value="light.jpg">Light</option>
<option value="help.jpg">Help</option>
<option value="camera.jpg">Camera</option>
</select>
<br /><br />
<label for="pwrIndex">Power Button Menu Index</label>
<input type="text" name="pwrIndex" id="pwrIndex"/ >
</div>
i have between 5-10 divs that will all be structured the same way just with different labels and input values.
i tried adding all the divs to an array and then enumerate through the array but that did not work.
here is my js file what i have tried:
{
const bar = document.querySelector('options');
var opts = document.querySelectorAll('.opt')
var option = {}
var nCount = $(".opt").length;
var divArray = [];
var optName = document.getElementById('optionName');
function addArray() {
for (let i = 0; i < nCount; i++) {
divArray[i] = opts[i];
}
}
const saveBtn = document.getElementById('submit');
saveBtn.addEventListener('click', (e) => {
putSettings();
});
function SystemOptions(optionName, optionAvailable, optionLabel, optionGraphic, optionIndex) {
this.optionName = optionName;
this.optionAvailable = optionAvailable;
this.optionLabel = optionLabel;
this.optionGraphic = optionGraphic;
this.optionIndex = optionIndex;
}
async function putSettings() {
let info = {
"SystemConfiguration": {
"Options": [],
}
}
addArray()
console.log(`Divarray = ${divArray.length}`)
//The following would never work
opts.forEach(label => {
$('[id=optionName]').each(function () {
var atId = this.id;
console.log(`Searched Name = ${atId.innerHTML}`)
});
});
divArray.forEach(element => {
var name = divArray.getElementById('optionName').innerHTML;
console.log(name)
option = new SystemOptions(name, "yes", "Help Label", "Option.jpeg", 3);
info.SystemConfiguration.Options.push(option);
});
for (let i = 0; i < nCount; i++) {
// console.log(` ${$(".opt").find("h2[id=optionName").each.text()}`)
console.log(` ${divArray[i].querySelector(optName[i]).innerHTML}`)
}
// i did this once to see if the SystemsOptions function worked
// obviosly it added the same data 7 times but i was trying to be sure the function worked and created the json objects
for (let i = 1; i < nCount; i++) {
option = new SystemOptions("Power", "yes", "Help Label", "Option.jpeg", 3);
info.SystemConfiguration.Options.push(option);
}
let data = JSON.stringify(info, 0, 4);
console.log(data);
}
}
any help would be greatly appreciated.
not the most eloquent but this does work.
sure there are better ways:
var opts = document.querySelectorAll('.opt');
var option = {};
const saveBtn = document.getElementById('submit');
saveBtn.addEventListener('click', (e) => {
putSettings();
});
function SystemOptions(optionName, optionAvailable, optionLabel, optionGraphic, optionIndex) {
this.optionName = optionName;
this.optionAvailable = optionAvailable;
this.optionLabel = optionLabel;
this.optionGraphic = optionGraphic;
this.optionIndex = optionIndex;
}
async function putSettings() {
let info = {
"SystemConfiguration" :{
"Options": [],
}
};
for(var opt of opts)
{
var name = opt.getElementsByTagName('h2')[0].innerHTML;
let isAvailable = opt.getElementsByTagName("input")[0].value;
let optLabel = opt.getElementsByTagName("input")[1].value;
let optGraphic = opt.getElementsByTagName('select')[0].value;
let index = opt.getElementsByTagName("input")[2].value;
option = new SystemOptions(name, isAvailable, optLabel, optGraphic, index);
info.SystemConfiguration.Options.push(option);
}
console.log(`Number of options = ${opts.length}`)
let data = JSON.stringify(info, 0, 4);
console.log(data);
};

How can I refresh second select option when first select option is changed?

How can I refresh second select option when first select option is changed?
I am generating the array here for patient_code2:
//GENERATE NUMBERS FOR CYCLE
function patsient(selector) {
var i;
for (i = 1; i <= 99; i++) {
var text = '0' + i;
selector.options[i - 1] = new Option(text.substr(text.length - 2, 2));
}
}
patsient(document.getElementById("patient_code2"));
I am generating the array for patient_code here:
function myFunction(selector) {
var i;
for (i = 1; i <= 999; i++) {
var text = '00' + i;
selector.options[i - 1] = new Option(text.substr(text.length - 3, 3));
}
}
//usage:
myFunction(document.getElementById("patient_code"));
Here I am inserting the last value from database to the field:
//INSERT THE VALUE FROM DATABASE
var tsykkel_id = '<?php foreach ($tsykkel_id as $row){echo $row['patsiendi_tsykkel'];}?>';
$('#patient_code2')[0].options[parseInt(tsykkel_id)].selected = true;
$(document).ready().on('change', '#patient_code2', function () {
var index = $('option:selected', $(this)).index();
$('option', $(this)).each(function (i, x) {
if (i < index) { $(this).remove(); }
});
});
HTML
<select name="patient_code" data-placeholder="" id="patient_code" class="chosen-select form-control" tabindex="2">
</select>
<label class="control-label">Tsükkel:</label>
<select name="patient_code2" data-placeholder="" id="patient_code2" class="chosen-select form-control" tabindex="2">
</select>
So lets say that person chooses 002 from the first then the second should start from 01 again.
try this then. Code is tested.
$(document).ready().on('change','#patient_code2',function(){
var index = $('option:selected',$(this)).index();
$('option',$(this)).each(function(i,x){
if(i<index){$(this).remove();}
});
$('select#patient_code').prop('selectedIndex', 0);
});
fiddle : http://jsfiddle.net/roullie666/69j94ro6/2/
You can just start printing after the match has been found. I am writing both ways since you asked?
For javascript version use roullie's no point duplicating.
<?php
$flag = false;
foreach ($tsykkel_id as $row) {
if ($selected) {
$flag = true;
}
if ($flag) {
$row['patsiendi_tsykkel'];
}
}?>

How to add an option to a dropdown menu created by 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>")

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