Perfoming formulas/calculations based off of selections on a dropdown menu? - javascript

var stocks = [
['Apple',100,8998,723,7212],
['Microsoft',928,1992,821,2381]
];
var select = document.getElementById("selectStock");
for(var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
<select id="selectStock">
<option>Choose a stock</option>
</select>
I have multiple Javascript arrays of data (pulled from Excel) and have different functions that basically make calculations based on the row of the array. For example:
var stocks = [['Apple',100,8998,723,7212]['Microsoft,928,1992,821,2381]]
What I need to do is make a dropdown menu that will allow a user to select an option (Microsoft or Apple) and then based on this selection, will pull this value into the formula to make the calculations
document.write(Math.round(stocks[i][1] * 100)/100 + " dollars per share");
where i is the variable based off dropdown menu selection. Does this make sense? I'm not sure how to approach this, it's for a personal project. Thanks for the help!

https://jsfiddle.net/b22y3v85/
var select = document.getElementById("selectStock");
select.onchange = (e) => {
let index = stocks.indexOf(stocks.find(a => a.indexOf(e.target.value) > -1));
document.write(Math.round(stocks[index][1] * 100)/100 + " dollars per share");
};

Here is a working example, although you'll probably want to do something other than document.write the result.
var stocks = [
['Apple',100,8998,723,7212],
['Microsoft',928,1992,821,2381]
];
var select = document.getElementById("selectStock");
for(var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
function getPrice(stock) {
var price = false;
for (var a = 0; a < stocks.length; a++) {
if (stocks[a][0] == stock) {
price = stocks[a][1];
break;
}
}
if (!price) { alert("Incorrect choice."); return; }
document.getElementById("result").innerText = stock + " is currently " + (Math.round(price * 100)/100 + " dollars per share");
}
<select id="selectStock" onchange="getPrice(this.value);">
<option>Choose a stock</option>
</select>
<br><br>
<div id="result"></div>
EDIT: Shows result in a div on the page, instead of overwriting the page with document.write().

<select id="selectStock"></select>
<script type="text/javascript">
var stocks = [
['Apple',100,8998,723,7212],
['Microsoft',928,1992,821,2381]
];
var select = document.getElementById("selectStock");
for(var i = 0; i < stocks.length; i++) {
var opt = stocks[i][0];
var el = document.createElement("option");
el.innerHTML = opt;
el.value =stocks[i]+'';
select.appendChild(el);
}
select.addEventListener('change', function(e){
var val = e.currentTarget.value;
val = val.split(',');
val.shift();
callYourMethod(val);
});
</script>

Related

JS select correct line in select list

I am using this JS code to do some magic. Working perfect to get a variabele and remove unwanted text and display the correct text in a text field.
values 2 or 3 or 5 or 7 etc. in <input type="text" id="calc_dikte[0][]" name="calc_dikte[]" value="">
function copy_dikte()
{
var i;
var elems = document.getElementsByName('dxf_var_dikte_copy[]');
var elems_1 = document.getElementsByName('dxf_vars[]');
var elems_2 = document.getElementsByName('calc_dikte[]');
var elems_3 = document.getElementsByName('calc_ext[]');
var l = elems.length;
var z;
z=0;
for(i=0; i<l; i++)
{
if(elems_3[i].value == 'dxf')
{
elems[i].value = document.getElementById('dxf_var_dikte').value;
var elems_1_split_1 = (elems_1[i].value).split(elems[i].value+'=');
var elems_1_split_2 = (elems_1_split_1[1]).split(',');
if(isNaN(elems_1_split_2[0])) { elems_2[i].value = ''; }
else { elems_2[i].value = parseFloat(elems_1_split_2[0]); }
}
}
}
So this works, but now the form field has changed from text to select like:
<select id="calc_dikte[0][]" name="calc_dikte[]">
<option value="">
<option value="2|2000">2</option>
<option value="3|2000">3</option>
<option value="5|2000">5</option>
<option value="7|2000">7</option>
</select>
Therefore I have changed my JS code (with some tips from here) to:
function copy_dikte()
{
var i;
var elems = document.getElementsByName('dxf_var_dikte_copy[]');
var elems_1 = document.getElementsByName('dxf_vars[]');
var elems_2 = document.getElementsByName('calc_dikte[]');
var elems_3 = document.getElementsByName('calc_ext[]');
var l = elems.length;
var z;
z=0;
for(i=0; i<l; i++)
{
if(elems_3[i].value == 'dxf')
{
elems[i].value = document.getElementById('dxf_var_dikte').value;
var elems_1_split_1 = (elems_1[i].value).split(elems[i].value+'=');
var elems_1_split_2 = (elems_1_split_1[1]).split(',');
var sel = elems_2[i];
var val = parseFloat(elems_1_split_2[0]);
for(var m=0, n=sel.options.length; m<n; m++)
{
if(sel.options[i].innerHTML === val)
{
sel.selectedIndex = m;
break;
}
}
}
}
}
But this is not working, no item is selected in the select list, no errors are shown.
Please help me out change to a working code to have the correct line selected. It should not select on the value but in the text between the ><
option value="5|2000">5</option
If I check with
for(var m=0, n=sel.options.length; m<n; m++) {
alert('sel = '+sel.options[i].innerHTML+'\nval = '+val);
}
I see that val is correct. But sel is just the number as used in $i so 0 1 2
You are using a strict equals operator to compare a Number (parseFloat) agains .innerHTML, which is always a string.
Convert sel.options[i].innerHTML to a Number aswell:
if (parseFloat(sel.options[i].innerHTML) === val) {
sel.selectedIndex = m;
break;
}
If you want to filter out invalid numbers (NaNs), use !isNaN(val) aswell.
Code to get this working:
function copy_dikte()
{
var i;
var elems = document.getElementsByName('dxf_var_dikte_copy[]');
var elems_1 = document.getElementsByName('dxf_vars[]');
var elems_2 = document.getElementsByName('calc_dikte[]');
var elems_3 = document.getElementsByName('calc_ext[]');
var l = elems.length;
var z;
z=0;
for(i=0; i<l; i++)
{
if(elems_3[i].value == 'dxf')
{
elems[i].value = document.getElementById('dxf_var_dikte').value;
var elems_1_split_1 = (elems_1[i].value).split(elems[i].value+'=');
var elems_1_split_2 = (elems_1_split_1[1]).split(',');
var val = parseFloat(elems_1_split_2[0]);
var sel = elems_2[i];
var opts = sel.options;
for (var opt, j = 0; opt = opts[j]; j++)
{
if (opt.text == val)
{
sel.selectedIndex = j;
break;
}
}
}
}
}

Selected attribute in option tag

I have a dropdown that's populated through a loop. The selected attribute should be added when <%if o.getNextPage()%> is equal to i.
<select id="dropDown" onchange="display(this.value)">
var start = 1;
var end = noOfPages;
var options = "";
for (var i = start; i <= end; i++) {
options += "<option>" + i + "</option>";
}
document.getElementById("dropDown").innerHTML = options;
function display(e) {
document.getElementById("hidden").value = e;
document.invoiceForm.submit();
}
You can add value attribute to the option tag.
As suggested by #3Dos in comments you can use ‘document.createElement‘ without needing to insert raw HTML like this:
var start = 1;
var end = noOfPages;
var options = "";
for (var i = start; i <= end; i++) {
var opt = document.createElement('option');
opt.value = i;
opt.innerHTML = i;
document.getElementById('dropDown').appendChild(opt);
}
This is the proper way of generating your dropdown list and preserve performance as you interact with the DOM only once thanks to the documentFragment
// These were not provided by OP but added to actually get this snippet running
var noOfPages = 5;
var start = 1;
var end = noOfPages;
var options = document.createDocumentFragment();
for (var i = start; i <= end; i++) {
var option = document.createElement('option');
option.value = i;
option.textContent = i;
options.appendChild(option);
}
document.getElementById("dropDown").appendChild(options);
<select id="dropDown" onchange="display(this.value)"></select>
I omitted the display function which is irrelevant as it refers to unprovided code.

How to set element value of dynamically created drop down?

I used arrays of strings to populate drop downs. How do I set the value of each drop down option to the same as the text content?
el.value = opt; doesn't appear to work.
var validCoursesKeys = ['opt 1','opt 2','opt 3','opt 4']
var validKeys = document.getElementsByClassName("validKeys");
setFields("courses");
function setFields(browser) {
//document.getElementById("result").value = browser;
var menuCounter = 1;
if (browser == "courses") {
for (var i = 0; i < validCoursesKeys.length; i++) {
var opt = validCoursesKeys[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
for (var j = 0; j < validKeys.length; j++) {
var elementClone = el.cloneNode(true);
elementClone.id = menuCounter;
menuCounter++;
validKeys[j].appendChild(elementClone);
}
}
} else if (browser == "rooms") {
var menuCounter = 1;
for (var i = 0; i < validRoomsKeys.length; i++) {
var opt = validRoomsKeys[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
for (var j = 0; j < validKeys.length; j++) {
var elementClone = el.cloneNode(true);
elementClone.id = menuCounter;
menuCounter++;
validKeys[j].appendChild(elementClone);
}
}
}
};
<select class="validKeys"></select>
<select class="validKeys"></select>
<select class="validKeys"></select>
You can achieve this using jquery. See below updated code using jquery
var validKeys = document.getElementsByClassName("validKeys");
function setFields(browser) {
//document.getElementById("result").value = browser;
var menuCounter = 1;
if (browser == "courses") {
$.each(validCoursesKeys , function(index, keys) {
var content='<option value="' + keys + '">' + keys + '</option>';
validKeys.append(content);
});
} else if (browser == "rooms") {
var menuCounter = 1;
$.each(validRoomsKeys , function(index, keys) {
var content='<option value="' + keys + '">' + keys + '</option>';
validKeys.append(content);
});
}
};

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);
}
}
}

Jquery get selected option's value and custom attribute value

var x = document.getElementById("selectCity");
var options = ["Bangalore", "Pune", "Kolkata"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var element = document.createElement("option");
element.textContent = opt;
element.value = opt;
x.appendChild(element);
}
$('select[name="cityDropdown"]').change(function(){
cityName=$(this).val();
});
Now with each city i want to store my circle name. and save it as an attribute and pass when the city is selected
You can Hardcode a custom attribute to a select's option. For example,
<option circle="UP" value="Lucknow">Lucknow</option>
and get it's value with jquery like this,
var circle = $('option:selected', this).attr("circle");
HTML
<select name="cityDropdown">
<option circle="UP" value="Lucknow">Lucknow</option>
<option circle="Bihar" value="Patana">Patana</option>
<option circle="Punjab" value="Chandigarh">Chandigarh</option>
</select>
Javascript
$('select[name="cityDropdown"]').change(function(){
var cityName = $(this).val();
var circle = $('option:selected', this).attr("circle");
console.log(cityName + " : " + circle);
});
Note : You can also use other custom attribute (custom attribute city for example). But you just need to use city as value of the option.
Here is the fiddle.
make a proper selector ..try this ..
$('#selectCity').change(function(){
cityName = $(this).val();
console.log(cityName); // do something
});
HERE is the fiddle..
var x = document.getElementById("selectCity");
var options = ["Bangalore", "Pune", "Kolkata"];
for(var i = 0; i < options.length; i++) {
var opt = options[i];
var element = document.createElement("option");
element.textContent = opt;
element.value = opt;
element.setAttribute('circle-name', 'your value'); // your attribute
x.appendChild(element);
}
$('select[name="cityDropdown"]').change(function(){
cityName=$(this).val();
});
var optionAttr = $('#cityDropdown option:selected').attr("circle");
var optionAttr1 = $(this).find('option:selected').attr("circle");

Categories