Trying to reset select options based on change w/out jQuery - javascript

I'm working in an environment where I can't use jQuery. I want to update options in one select box when options in another select box are changed. What I have now doesn't totally clear out the prior set of options or it's adding options I don't want.
I want the entity options to be dependent on the sponsor option selected.
https://codepen.io/dzamora54/pen/poogwJN
<label for="sponsorDropdown">Sponsor</label>
<select name="sponsorDropdown" id="sponsorDropdown">
<option disabled selected value>Select an option</option>
</select>
<label for="entityDropdown">Entity</label>
<select name="entityDropdown" id="entityDropdown">
<option disabled selected value>Select an option</option>
</select>
// List of sponsors
const sponsorList = [
{
sponsorName: "Sponsor One",
sponsorEntities: ["Sp1 Entity One", "Sp1 Entity Two", "Sp1 Entity Three"],
sponsorSigners: [
{ signerName: "Sp1 Signer One", signerTitle: "Sp1 Si1 Title" },
{ signerName: "Sp1 Signer Two", signerTitle: "Sp1 Si2 Title" }
]
},
{
sponsorName: "Sponsor Two",
sponsorEntities: ["Not Applicable"],
sponsorSigners: [
{ SignerName: "Sp2 Signer One", signerTitle: "Sp2 Si1 Title" }
]
},
{
sponsorName: "Sponsor Three",
sponsorEntities: ["Not Applicable"],
sponsorSigners: [
{ signerName: "Sp3 Signer One", signerTitle: "Sp3 Si1 Title" },
{ signerName: "Sp3 Signer Two", signerTitle: "Sp3 Si2 Title" }
]
}
];
let sponsorValue;
let sponsorIndex;
// On load calls populateSponsorDropdown function
window.addEventListener("load", function() {
this.populateSponsorDropdown();
});
// Populates sponsor dropdown from list of sponsors
function populateSponsorDropdown() {
for (let i = 0; i < sponsorList.length; i++) {
let sponsor = document.getElementById("sponsorDropdown");
let option = document.createElement("option");
option.text = sponsorList[i].sponsorName;
sponsor.add(option);
}
}
// When sponsor dropdown changes, update entity dropdown as neccessary
document
.getElementById("sponsorDropdown")
.addEventListener("change", updateSponsorValueAndEntityDropdown);
function updateSponsorValueAndEntityDropdown() {
sponsorValue = document.getElementById("sponsorDropdown").value;
for (let i = 0; i < sponsorList.length; i++) {
if (sponsorValue === sponsorList[i].sponsorName) {
sponsorIndex = i;
}
}
populateEntityDropdown();
}
// Populates entity dropdown based on sponsor that is selected
function populateEntityDropdown() {
const emptyDropdown = document.getElementById("entityDropdown");
const length = emptyDropdown.options.length;
for (i = 0; i < length; i++) {
emptyDropdown.options[i] = null;
}
// for (let i = 0; i < entityDropdown.length; i++) {
// let emptyDropdown = document.getElementById("entityDropdown");
// emptyDropdown.remove(i);
for (let j = 0; j < sponsorList[sponsorIndex].sponsorEntities.length; j++) {
let entity = document.getElementById("entityDropdown");
let option = document.createElement("option");
option.text = sponsorList[sponsorIndex].sponsorEntities[j];
entity.add(option);
}
}

I think I solved this by replacing
const emptyDropdown = document.getElementById("entityDropdown");
const length = emptyDropdown.options.length;
for (i = 0; i < length; i++) {
emptyDropdown.options[i] = null;
with
const emptyDropdown = document.querySelector("#entityDropdown");
emptyDropdown.innerHTML = "";

Related

Concatenating text to options with a certain data attribute value

I have a select element:
function find() {
var schoolList = document.getElementByID("schoolList");
if (schoolList.hasAttributes("[data attribute value]") {
//modify text in found option
};
};
find();
<div id="SelectWrapper" class="menu">
<form>
<select id="schoolList">
<option value='student' data-tier="student" data->Student 1</option>
<option value="teacher" data-tier="faculty" data->Teacher</option>
</form>
</div>
Using pure Javascript, I want to create an if statement within a function that checks to see if an option has an appropriate data attribute value (for instance, "student" or "faculty") and then adds to or modifies the existing innerHTML/text.
You can use querySelectorAll() to find all the options with a particular data value, then loop over them.
function find() {
var options = document.querySelectorAll("#schoolList option[data-tier=student]");
for (var i = 0; i < options.length; i++) {
options[i].innerHTML += " (something)";
}
}
The example for you
function find() {
var schoolList = document.getElementById("schoolList");
if (schoolList.hasAttributes("[data attribute value]")) {
var opts = schoolList.getElementsByTagName("option");
for (var i = 0, len = opts.length; i < len; i++) {
var option = opts[i];
// modify
if (option["data-tier"] === "student") {
option.text = "new text content"
}
}
// add new
for (var i =0; i < 5; i++) {
var opt = document.createElement("option");
opt.value = i;
opt.innerHTML = "Option " + i;
schoolList.appendChild(opt);
}
};
};
find();

Function not running on button click? [duplicate]

This question already has answers here:
Is "clear" a reserved word in Javascript?
(4 answers)
Closed 6 years ago.
I have a button on my page that is intended to clear all the textareas that are in the document, however when I click said button it appears that the function isn't being run. I've tried adding a button listener to the document, and that still didn't seem to work, I don't understand what the problem is, as the line with the alert isn't even running.
function markForm(tagID) {
var x = document.getElementById(tagID)
var pre = document.createElement("pre");
x.appendChild(pre);
var SectionDetails = [
{ name: "Dynamic Table", maxMarks: 20},
{ name: "IntelliJ usage", maxMarks: 10},
{ name: "Calendar Controller", maxMarks: 30},
{ name: "Active Form", maxMarks: 20},
{ name: "Object Database", maxMarks: 20}
];
var table = pre.appendChild(document.createElement("table"));
var tableHeader = table.appendChild(document.createElement("thead"));
var tableRow = tableHeader.appendChild(document.createElement("tr"));
var headRow = tableRow.appendChild(document.createElement("th"));
headRow.appendChild(document.createTextNode("Section"));
headRow = tableRow.appendChild(document.createElement("th"));
headRow.appendChild(document.createTextNode("Max Mark"));
headRow = tableRow.appendChild(document.createElement("th"));
headRow.appendChild(document.createTextNode("Comments"));
headRow = tableRow.appendChild(document.createElement("th"));
headRow.appendChild(document.createTextNode("Mark"));
var resultsRows = table.appendChild(document.createElement("tbody"));
for (var i = 0; i < SectionDetails.length; i++) {
tableRow = resultsRows.appendChild(document.createElement("tr"));
var tableData = tableRow.appendChild(document.createElement("td"));
tableData.appendChild(document.createTextNode(SectionDetails[i].name));
tableData = tableRow.appendChild(document.createElement("td"));
tableData.appendChild(document.createTextNode(SectionDetails[i].maxMarks));
tableData = tableRow.appendChild(document.createElement("td"));
var tarea = document.createElement("textarea");
tarea.value = "Enter Comments";
tableData.appendChild(tarea);
tableData = tableRow.appendChild(document.createElement("td"));
var dropDown = document.createElement("select");
dropDown.name = SectionDetails[i].name;
for (var j = 0; j < (SectionDetails[i].maxMarks + 1); j++) {
var listItem = new Option(j);
listItem.value=j;
dropDown.appendChild(listItem);
}
tableData.appendChild(dropDown);
}
var h2 = document.createElement("h2");
h2.innerHTML = "Total Marks: " + document.createTextNode(totalMarks);
x.appendChild(h2);
}
function totalMarks() {
var total = 0;
for (var a = 0; a < SectionDetails.length; a++) {
var e = document.getElementById(SectionDetails[a].name);
var total = total + Number(e.options[e.selectedIndex].value);
}
return total;
}
function clear() {
var textareas = documents.getElementsByTagName("textarea");
console.log(textareas);
for (var i = 0; i < textareas.length; i++) {
textareas[i].value="Enter Comments";
}
alert("Fields Cleared");
}
<body onload="markForm('conversion')">
<h2>Marking Form: </h2>
<p id='conversion'>
</p>
<p id='clear'>
<input type="button" id="but" value="Clear" onclick="clear()"/>
</p>
There seems an error in your clear() function. it should be document.getElementsByTagName(). and yours is "documents" - also clear is a word used elsewhere: document.clear

How to update options of select but keep previously selected one as selected?

Here's my try on implementing this:
var select = document.getElementById(key);
var temp = select.value;
select.options.length = 0; // clear out existing items
for (var i = 0; i < data.length; i++) {
select.options.add(new Option(data.Value, data.Key))
}
select.value = temp;
In case of there is no such value anymore I would like to set some default values for selcted option.
This is a simple function called init_select
It clear the selection tag
-remembers the option that was previously selected
if the item that was previously selected item is not in the list of new options..it will select the option that you want (this is the default_opt) parameter
-if the previously item is IN the list it will ignore the default_opt paramater and use the previously selected item.
demo here (previously selected item NOT in list but default_opt is IN list)
function init_select(id,data,default_opt) {
var select = document.getElementById(id);
var temp = select.value;
select.innerHTML="";
for (var i = 0; i < data.length; i++) {
select.options.add(new Option(data[i]))
}
if (data.indexOf(temp) < 0 && data.indexOf(default_opt)>=0 ) {
select.value = default_opt;
console.log('this is select',select.value,default_opt,select);
} else if (data.indexOf(temp) >= 0){
//select.options.add(new Option(temp));
select.value = temp;
console.log(select.value,data.indexOf(temp));
}
}
init_select('key',["New Value", "New Value2", "New Value3", "New Value4"],"New Value2")
<select id="key">
<option>year1</option>
<option>year2</option>
<option>year3</option>
</select>
demo here (previously selected item IN list and default_opt is IN list, default options is ignored and the previously selected item is selected)
function init_select(id,data,default_opt) {
var select = document.getElementById(id);
var temp = select.value;
select.innerHTML="";
for (var i = 0; i < data.length; i++) {
select.options.add(new Option(data[i]))
}
if (data.indexOf(temp) < 0 && data.indexOf(default_opt)>=0 ) {
select.value = default_opt;
console.log('this is select',select.value,default_opt,select);
} else if (data.indexOf(temp) >= 0){
//select.options.add(new Option(temp));
select.value = temp;
console.log(select.value,data.indexOf(temp));
}
}
init_select('key',["New Value", "New Value2", "New Value3", "New Value4","year1"],"New Value2")
<select id="key">
<option>year1</option>
<option>year2</option>
<option>year3</option>
</select>
Your idea of getting the value of select and resetting it was right. You can achieve your wanted result with jQuery like this.
Note that if the old value is not available, select's value will be set to null.
$("button").on("click", function() {
var def = "4. Option";
var temp = $("select").val();
var select = $("select");
select.empty();
for (i = 2; i <= 10; i++) {
$("<option>").text(i + ". Option").appendTo(select);
}
select.val(temp);
if (select.val() == null)
select.val(def);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option>1. Option</option>
<option>2. Option</option>
<option>3. Option</option>
<option>4. Option</option>
<option>5. Option</option>
</select>
<button>Clear and Fill Select</button>

How to get my JS script to run when select option is changed

I have a JS script to add another select option when the first one has been selected however when I load the page and change the Value I get no result from my script I've ran it through JS Bin and there aren't any syntax errors and no warnings and now I am stuck. Is there some method of getting the result I am looking for??
here is the JS script
function bevfoo()
{
var value = document.getElementById("pre").value;
var select = document.getElementById("tod");
var tod = document.createElement("select");
var food = ["one", "two"];
var drink = ["two", "one"];
if(value === "Food")
{
for(var i = 0; i < food.length; i++)
{
var option = document.createElement("option");
option.text = food[i];
tod.appendChild(option);
}
}
else if(value === "Beverage")
{
for(var d = 0; d < drink.length; d++)
{
var option2 = document.createElement("option2");
option2.text = drink[d];
tod.appendChild(option2);
}
}
}
and my HTML code that's supposed to call the JS function that's above
<DIV ID="classification">
<P>Food / Beverage:
<SELECT NAME="class1" ID="pre" ONCHANGE="bevfoo()">
<OPTION DISABLED>---Select One---</OPTION>
<OPTION>Food</OPTION><OPTION>Beverage</OPTION>
</SELECT><P>
<P ID="tod">Time Of Day: </P>
</DIV>
You need to add the created select to the tod element
function bevfoo() {
var value = document.getElementById("pre").value;
var select = document.getElementById("tod");
var tod = select.querySelector('select');
//if the select already exists then use it, else create and append to select
if (!tod) {
tod = document.createElement("select");
select.appendChild(tod)
}
var food = ["one", "two"];
var drink = ["two", "one"];
tod.innerHTML = '';
if (value === "Food") {
for (var i = 0; i < food.length; i++) {
var option = document.createElement("option");
option.text = food[i];
tod.appendChild(option);
}
} else if (value === "Beverage") {
for (var d = 0; d < drink.length; d++) {
var option2 = new Option(drink[d])
tod.appendChild(option2);
}
}
}
bevfoo();
<DIV ID="classification">
<P>Food / Beverage:
<SELECT NAME="class1" ID="pre" ONCHANGE="bevfoo()">
<OPTION DISABLED>---Select One---</OPTION>
<OPTION>Food</OPTION>
<OPTION>Beverage</OPTION>
</SELECT>
</P>
<P ID="tod">Time Of Day: </P>
</DIV>
Simplified version
var optionsMap = {
Food: ["one", "two"],
Beverage: ["two", "one"]
};
function bevfoo() {
var value = document.getElementById("pre").value;
var select = document.getElementById("tod");
var tod = select.querySelector('select');
//if the select already exists then use it, else create and append to select
if (!tod) {
tod = document.createElement("select");
select.appendChild(tod)
}
tod.innerHTML = '';
var values = optionsMap[value]
if (values) {
for (var i = 0; i < values.length; i++) {
tod.appendChild(new Option(values[i]));
}
}
}
//set the initial value
bevfoo();
<DIV ID="classification">
<P>Food / Beverage:
<SELECT NAME="class1" ID="pre" ONCHANGE="bevfoo()">
<OPTION DISABLED>---Select One---</OPTION>
<OPTION>Food</OPTION>
<OPTION>Beverage</OPTION>
</SELECT>
</P>
<P ID="tod">Time Of Day: </P>
</DIV>
So the issue was that you were never attaching your select element in your dom. Just creating that element does not add it to your dom. Added the select element as a child of classification div.
Also, you had used select2 for beverages, which should have been select
Here's the fiddle for the same -
http://jsfiddle.net/mu8o7dqh/1/
function bevfoo()
{
var classification = document.getElementById("classification");
var value = document.getElementById("pre").value;
var select = document.getElementById("tod");
var tod = document.createElement("select");
var food = ["one", "two"];
var drink = ["two", "one"];
classification.appendChild(tod);
if(value === "Food")
{
for(var i = 0; i < food.length; i++)
{
var option = document.createElement("option");
option.text = food[i];
tod.appendChild(option);
}
}
else if(value === "Beverage")
{
for(var d = 0; d < drink.length; d++)
{
var option2 = document.createElement("option");
option2.text = drink[d];
tod.appendChild(option2);
}
}
}

javascript dropdown list choice dependent on previous selection

I have had to go back to the drawing board as my previous js did not work with my new database structure.
I can not figure out how to use JavaScript to populate a dropdown list dependent on the previous dropdown list selections
I have 5 drop down lists in total with the options selected dependent on the previous choices selected.
The issue I have is the dropdown boxes being created do not send their value when using GET on form submission and I am unaware for how to define that value.
Please can someone give me advice on creating these dropdown lists? Google searches are bringing up ideas but not sufficient for anything with more than 2 drop down lists.
thanks
html
<select id="product" name="products" onchange="configureDropDownLists(this,'faulttype')">
<option value="">select</option>
<option value="test1">test1</option>
<option value="test2">test2</option>
<option value="test3">test3</option>
<option value="test4">test4</option>
</select>
Fault Type:
<select id="faulttype" name="faulttypes" onchange="configureDropDownLists2(this,'faulttype2')">
<option>{blank}</option>
</select>
Fault Type2:
<select id="faulttype2" name="faulttypes2" onchange="configureDropDownLists3(this,'faulttype3')">
<option>{blank}</option>
</select>
Fault Type3:
<select id="faulttype3" name="faulttypes3">
<option>{blank}</option>
</select>
<input type="submit" value="Search">
</fieldset>
js
var test1 = new Array('test5', 'test6', 'test7');
var test2 = new Array('test8', 'test9', 'test10');
var test3 = new Array('test11', 'test12', 'test13');
var test4 = new Array('test14', 'test15', 'test16');
switch (product.value) {
case 'test1':
document.getElementById(faulttype).options.length = 0;
for (i = 0; i < test1.length; i++) {
createOption(document.getElementById(faulttype), test1[i], test1[i]);
}
break;
case 'test2':
document.getElementById(faulttype).options.length = 0;
for (i = 0; i < test2.length; i++) {
createOption(document.getElementById(faulttype), test2[i], test2[i]);
}
break;
case 'test3':
document.getElementById(faulttype).options.length = 0;
for (i = 0; i < test3.length; i++) {
createOption(document.getElementById(faulttype), test3[i], test3[i]);
}
break;
case 'test4':
document.getElementById(faulttype).options.length = 0;
for (i = 0; i < test4.length; i++) {
createOption(document.getElementById(faulttype), test4[i], test4[i]);
}
function configureDropDownLists2(faulttype, faulttype2) {
var test5 = new Array('test15', 'test14');
var test6 = new Array('test16', 'test17');
switch (faulttype.value) {
case 'test5':
document.getElementById(faulttype2).options.length = 0;
for (i = 0; i < test5.length; i++) {
createOption1(document.getElementById(faulttype2), test5[i], test5[i]);
}
break;
case 'test6':
document.getElementById(faulttype2).options.length = 0;
for (i = 0; i < test6.length; i++) {
createOption1(document.getElementById(faulttype2), test6[i], test6[i]);
}
break;
}
function createOption1(ddl, text, value) {
var opt = document.createElement('option');
var ddl = document.getElementById('faulttype2');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}

Categories