reset a drop down list value to previous value - javascript

I am using javascript to validate some drop down list selections. One selection is for the length of a buildings frame. The other 3 drop down are for garage doors that can be added to the side. I have the code alerting me if the total door widths have exceeded the frame length. I need the if condition to take the previous value of the last selected door drop down list and reset it to the amount before it if the amount exceeds my conditions in my if statement.
This is my html
Frame Length:
<select id="framewidth" onchange="doorsrightsideFunction()">
<option value="20">21</option>
<option value="25">26</option>
<option value="30">31</option>
<option value="35">36</option>
<option value="40">41</option>
</select>
<br>
<input type="hidden" name="eight_by_seven_width_right_side"
id="eight_by_seven_width_right_side" value="8">
<br>
<input type="hidden" name="eight_by_seven_height_right_side"
id="eight_by_seven_height_right_side" value="7">
<br>8x7:
<select id="eight_by_seven_right_side" onchange="doorsrightsideFunction()">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<input type="hidden" name="nine_by_seven_width_right_side"
id="nine_by_seven_width_right_side" value="9">
<br>
<input type="hidden" name="nine_by_seven_height_right_side"
id="nine_by_seven_height_right_side" value="7">
<br>9x7:
<select id="nine_by_seven_right_side" onchange="doorsrightsideFunction()">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<br>
<input type="hidden" name="ten_by_eight_width_right_side"
id="ten_by_eight_width_right_side" value="10">
<br>
<input type="hidden" name="ten_by_eight_height_right_side"
id="ten_by_eight_height_right_side" value="8">
<br>10x8:
<select id="ten_by_eight_right_side" onchange="doorsrightsideFunction()">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
This is my javascript so far
function doorsrightsideFunction() {
function getValue(idElement) {
return document.getElementById(idElement).value;
}
var eightwidth = getValue("eight_by_seven_width_right_side");
var ninewidth = getValue("nine_by_seven_width_right_side");
var tenwidth = getValue("ten_by_eight_width_right_side");
var eightwidthamount = getValue("eight_by_seven_right_side");
var ninewidthamount = getValue("nine_by_seven_right_side");
var tenwidthamount = getValue("ten_by_eight_right_side");
var framewidth = getValue("framewidth");
var totaldoorwidth;
var totaldooramount;
var framewidthtotaldoorwidth;
var framespace;
totaldoorwidth = eightwidth * eightwidthamount
+ ninewidth * ninewidthamount
+ tenwidth * tenwidthamount;
totaldooramount = parseInt(eightwidthamount, 10)
+ parseInt(ninewidthamount, 10)
+ parseInt(tenwidthamount, 10);
framewidthtotaldoorwidth = framewidth - totaldoorwidth;
framespace = totaldooramount + 1;
if (framewidthtotaldoorwidth < framespace) {
alert("You have to many doors on the right side");
} else { }
}
here is a link to my fiddle http://jsfiddle.net/steven27030/M52Hf/

http://jsfiddle.net/M52Hf/84/
you could use the data attribute and be sure to pass in the current element as a parameter on your doorsrightsideFunction call:
<select id="framewidth" onchange="doorsrightsideFunction(this)">
var previousValue = currentelement.getAttribute("data-prev");
if(previousValue == null)
previousValue = currentelement[0].value;

You will need to store the previous value so you can switch back when necessary, and update the previous value after a successful change. I would use arrays in various places.
var prevValue = Array();
function doorsrightsideFunction() {
function getValue(idElement) {
return document.getElementById(idElement).value;
}
function setValue(idElement,val) {
return document.getElementById(idElement).value = val;
}
var ids = Array("eight_by_seven_right_side","nine_by_seven_right_side","ten_by_eight_right_side");
var widths = Array(
getValue("eight_by_seven_width_right_side"),
getValue("nine_by_seven_width_right_side"),
getValue("ten_by_eight_width_right_side")
);
var values = Array();
for(i=0;i<ids.length;i++) {
if (!prevValue[i]) { prevValue[i]=0; }
values[i] = getValue(ids[i]);
}
var framewidth = getValue("framewidth");
var totaldoorwidth = 0;
var totaldooramount = 0;
var framewidthtotaldoorwidth;
var framespace;
for(i=0;i<ids.length;i++) {
totaldoorwidth += values[i] * widths[i];
totaldooramount += parseInt(values[i], 10);
}
framewidthtotaldoorwidth = framewidth - totaldoorwidth;
framespace = totaldooramount + 1;
if (framewidthtotaldoorwidth < framespace) {
alert("You have to many doors on the right side");
for(i=0;i<ids.length;i++) { setValue(ids[i],prevValue[i]); }
} else {
prevValue = values;
}
}
updated fiddle
Edit: In answer to your follow on question in the comment:
is there a way to make it loop through and find the next size down that would work if they choose to many?
Yes, you can have it iterate the values to find one that fits, as long as the initial values are valid (in this case no doors is a perfect initial value). This also means you don't need to worry about storing any previous value.
I had some fun with this a took some liberties with your code.
First, a few changes in the HTMl:
for each element with an onChange, have it pass the element that was changed so we can tell which one to modify:
<select ... onchange="doorsrightsideFunction(this)">
change the IDs of the _width and _height hidden inputs so they are of the form <id of select element>_width (i.e. the width element for the select with id="eight_by_seven_right_side" should be "eight_by_seven_right_side_width" so you just need to take id + "_width" to find it)
wrap all of the door select elements in a <div id="doorchoices"> ... </div> so they can be found programmatically. This way adding a new door to the system is as simple as adding the select and height/width hidden inputs within the containing div, and the javascript finds and uses them automagically.
The javascript changes, I tried to comment inline:
//make ids and widths global to this page so we only have to construct it on page load
var ids;
var widths;
function getValue(idElement) {
var el = document.getElementById(idElement);
if (el) {
return parseInt(el.value);
} else {
return null;
}
}
function setValue(idElement, val) {
return document.getElementById(idElement).value = val;
}
window.onload = function () {
//construct id list from elements within the containing div when the page loads
ids = Array("framewidth");
widths = Array(null);
var container = document.getElementById("doorchoices");
var selections = container.getElementsByTagName("select");
var i;
for (i = 0; i < selections.length; i++) {
ids.push(selections[i].id);
// get each door's width from the _width element that matches the id
widths.push(getValue(selections[i].id + "_width"));
}
}
// el is the 'this' passed from the select that changed
function doorsrightsideFunction(el) {
console.log(widths);
console.log(ids);
var changedIndex = ids.indexOf(el.id);
//get all of the option elements of the changed select
var possibleValueEls = el.getElementsByTagName("option");
var values = Array();
var possibleValues = Array();
var framewidth;
var curValue;
var totaldoorwidth;
var totaldooramount;
var framewidthtotaldoorwidth;
var framespace;
var i;
function calcWidth() {
totaldoorwidth = 0;
totaldooramount = 0;
var i;
framewidth = values[0];
//start with 1 since index 0 is the frame width
for (i = 1; i < ids.length; i++) {
console.log(i + ")" + ids[i] + " " + values[i] + "(" + widths[i] + ")");
totaldoorwidth += values[i] * widths[i];
totaldooramount += parseInt(values[i], 10);
}
framewidthtotaldoorwidth = framewidth - totaldoorwidth;
framespace = totaldooramount + 1;
}
// get all possible values from the option elements for the select that was changed
for (i = 0; i < possibleValueEls.length; i++) {
possibleValues.push(parseInt(possibleValueEls[i].value));
}
// values should be increasing in order
possibleValues.sort();
// except framewidth should be decreasing
if (el.id == "framewidth") {
possibleValues = possibleValues.reverse()
};
// get the value of each element
for (i = 0; i < ids.length; i++) {
values[i] = getValue(ids[i]);
if (changedIndex == i) {
curValue = values[i]
};
}
calcWidth();
console.log(framewidthtotaldoorwidth);
console.log(framespace);
if (framewidthtotaldoorwidth < framespace) {
alert("You have to many doors on the right side");
// start with the current value and try each until it fits
for (validx = possibleValues.indexOf(curValue); validx >= 0, framewidthtotaldoorwidth < framespace; validx--) {
//change the value in the values array
values[changedIndex] = possibleValues[validx];
//change the select to match
setValue(el.id, possibleValues[validx]);
//see if it fits
calcWidth();
}
}
}
New fiddle
and the simplicity of adding another door size - just add this to the HTML:
<input type="hidden" name="twelve_by_ten_right_side_width" id="twelve_by_ten_right_side_width" value="12" />
<input type="hidden" name="twelve_by_ten_right_side_height" id="twelve_by_ten_right_side_height" value="10" />
<br />
<label for="twelve_by_ten_right_side">12x10:</label>
<select id="twelve_by_ten_right_side" onchange="doorsrightsideFunction(this)">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
New door fiddle

Related

Append options to select box depend on extracted part from array

I have 4 selectboxs moduleName, submoduleName, ProgrameName and last selectbox has all data for username, module, submodule and programe name merged and splited with ";" between each other, I need: when user select module name from moduleName Selectbox it filters values in all data selectbox and splites submoduleNames under this moduleName and append it as options to submoduleName Selectbox, also the same when user select from submoduleName selectbox it filters programeNames under this module and subModuleNames and append it as options in programeName selectbox. I tried to splite each line in allData selectbox but i failed to continue. here what i tried but it is not working.
Thank you for your help.
$(document).ready(function(){
function check(){
var lines = $('#splitedOptions').val().split(/\n/);
var texts = [];
for (var i=1; i < lines.length; i++) {
texts.push(lines[i]);
}
for (var i=0; i < texts.length; i++) {
var extractedPart = texts[i].split(';'),
ModuleNameVal = $("#moduleName option:selected").val();
if(extractedPart[1] == ModuleNameVal){
var newOption = "<option value='"+extractedPart[2]+"'>"+extractedPart[2]+"</option>";
$('#SubModuleName').append(newOption);
}
}
}
function c1() {
var optionsCount = $('#allData').find('option').size();
var textArea ="";
for (var i = 1; i <= optionsCount; i++) {
if(i!=1){
textArea += '\n';
}
var xItem = $('#allData').find('option:nth-child(' + (i) + ')').text();
textArea += xItem ;
}
$('#splitedOptions').val('');
$('#splitedOptions').val(textArea);
check();
}
$('#moduleName').change(function(){
c1()
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>ModuleName:</label>
<select class="moduleName" id="moduleName">
<option value="HR">HR</option>
<option value="Marketing">Marketing</option>
<option value="Purchase">Purchase</option>
<option value="Finance">Finance</option>
</select><br><br>
<label>SubModuleName:</label>
<select class="SubModuleName" id="SubModuleName"></select><br><br>
<label>ProgrameName:</label>
<select class="programeName" id="programeName"></select><br><br>
<label>All Data:</label>
<select class="allData" id="allData">
<option value="userName;HR;Transactions;EmployeeMaster">Option1</option>
<option value="userName;HR;Master;EmployeeMaster">Option2</option>
<option value="userName;Marketing;Master;MarketingMaster">Option3</option>
<option value="userName;HR;Reports;HRReports">Option4</option>
<option value="userName;Purchase;PurchaseOrders;LPO">Option5</option>
<option value="userName;Purchase;PurchaseOrders;IPO">Option6
<option value="userName;Finance;Master;FinanceMasterPrograme">Option7</option>
<option value="userName;Finance;Reports;FinanceReportsPrograme">Option8</option>
</select><br><br>
<label>splited Options:</label>
<textarea id="splitedOptions" name="splitedOptions" ></textarea>
One way to achieve above is to filter the options from allData select-box and get only those option which has the value which user has selected using value*="yourvalue".
Then , onces you get the options you need to know which select-box has been change so that we can get required value only when we do split and pass required index .
Lastly , we need to loop through the options which we have got from filtering select-box .Suppose user select Master so there are Master in many places so to avoid getting data from all option i have check the value of select with the first select-box as well if matches apppend only those options.
Demo Code :
$('select').change(function() {
//get value
var name = $(this).val();
//filter option and get only option which has the value which user has slected
var s = $("#allData").find('option').filter('[value*=' + name + ']').each(function(ele) {
return $(this).val();
});
var module_namess;
var index;
//check the id of select-box
if ($(this).attr("id") == "moduleName") {
module_namess = "SubModuleName";
index = 2;//set index
} else if ($(this).attr("id") == "SubModuleName") {
name = $("#moduleName").val()
module_namess = "programeName"
index = 3
}
$("#" + module_namess).empty()
$('#' + module_namess).append("<option >Select one</option>")
var valuess = ''
//loop through options
for (var i = 0; i < s.length; i++) {
valuess += $(s[i]).val()
//if first value is same
if ($(s[i]).val().split(";")[1] == name) {
var sub_value = $(s[i]).val().split(";")[index]//get the value
var newOption = "<option value='" + sub_value + "'>" + sub_value + "</option>";
$('#' + module_namess).append(newOption);//append
}
}
$('#splitedOptions').val(valuess);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>ModuleName:</label>
<select class="moduleName" id="moduleName">
<option value="HR">HR</option>
<option value="Marketing">Marketing</option>
<option value="Purchase">Purchase</option>
<option value="Finance">Finance</option>
</select><br><br>
<label>SubModuleName:</label>
<select class="SubModuleName" id="SubModuleName"></select><br><br>
<label>ProgrameName:</label>
<select class="programeName" id="programeName"></select><br><br>
<label>All Data:</label>
<select class="allData" id="allData">
<option value="userName;HR;Transactions;EmployeeMaster">Option1</option>
<option value="userName;HR;Master;EmployeeMaster">Option2</option>
<option value="userName;Marketing;Master;MarketingMaster">Option3</option>
<option value="userName;HR;Reports;HRReports">Option4</option>
<option value="userName;Purchase;PurchaseOrders;LPO">Option5</option>
<option value="userName;Purchase;PurchaseOrders;IPO">Option6
<option value="userName;Finance;Master;FinanceMasterPrograme">Option7</option>
<option value="userName;Finance;Reports;FinanceReportsPrograme">Option8</option>
</select><br><br>
<label>splited Options:</label>
<textarea id="splitedOptions" name="splitedOptions"></textarea>

Select values not correctly increasing/decreasing total number in js

I thought I had solved this javascript 'for' loop to sum up the numeric choices of several select fields to a number, each time one of them is changed.
But, modifying a choice in any of the selected fields is adding the number again, instead of replacing the initial choice number - which is what I want.
Example: a user chooses from 3 fields, these values: +15, -5, +1.
The total should be "11"
If the user modifies their first select to +10 instead of #+15, the total value should be "6". Instead, it's ADDING the modified number to everything. So the number becomes "21" - not what I want.
Note: I want to increase the number incrementally with each select choice - NOT a total of all of them when the user is done with the fields
Here's what I've got:
<form action="/cgi-bin/dropdown.cgi" method="post">
<select class="select0 selectables" id="dropdown-0" name="dropdown0">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="10">Choice 1 (+10)</option>
<option value="-5">Choice 2 (-5)</option>
<option value="60">Choice 3 (+60)</option>
</select>
<br />
<select class="select1 selectables" id="dropdown-1" name="dropdown1">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="8">Choice A (+8)</option>
<option value="-10">Choice B (-10)</option>
<option value="15">Choice C (+15)</option>
</select>
<br />
<select class="select2 selectables" id="dropdown-2" name="dropdown2">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="5">Choice ii (+5)</option>
<option value="15">Choice ii (+15)</option>
<option value="12">Choice iii (+12)</option>
</select>
</form>
<div id="tally" style="">0</div>
<script>
var sum = 0;
document.addEventListener("DOMContentLoaded", function(event) {
var gg1 = new JustGage({
id: "gg1",
value: 0,
textRenderer: customValue
});
var userSelection = document.getElementsByClassName('selectables');
for(let i = 0; i < userSelection.length; i++) {
userSelection[i].addEventListener("change", function() {
fieldvalue = userSelection[i].value;
fieldname = userSelection[i].id;
if (fieldvalue > 0) {
// using += breaks other scripts for some reason
sum = sum + parseInt(fieldvalue);
} else if (fieldvalue < 1) {
fieldvalue = fieldvalue * -1;
sum = sum - parseFloat(fieldvalue, 10);
}
document.getElementById("tally").innerHTML = sum;
// this is the value that takes the number I'm trying to increment based on choices in selects
gg1.refresh(sum);
return false;
})
}
});
</script>
This happens because inside the callback function of the change listener you're not considering the values of the other dropdowns. Grab them using a second for-loop and recalculate the sum.
Here's your modified callback function:
for (let i = 0; i < userSelection.length; i++) {
userSelection[i].addEventListener("change", function() {
sum = 0;
for (var b = 0; b < userSelection.length; b++) {
fieldvalue = userSelection[b].value;
if (fieldvalue > 0) {
// using += breaks other scripts for some reason
sum = sum + parseInt(fieldvalue);
} else if (fieldvalue < 1) {
fieldvalue = fieldvalue * -1;
sum = sum - parseFloat(fieldvalue, 10);
}
}
document.getElementById("tally").innerHTML = sum;
// this is the value that takes the number I'm trying to increment based on choices in selects
gg1.refresh(sum);
return false;
})
}
Whenever any of the select values is changed, you should re-compute the entire sum. Something like this:
onload = function {
var userSelection = document.getElementsByClassName('selectables');
for(let i = 0; i < userSelection.length; i++) {
userSelection[i].addEventListener("change", function() {
var sum= computeSum();
//whatever you want to do with sum
})
}
function computeSum() {
var sum = 0;
for(const select in userSelection) {
sum += select.value;
}
return sum;
}
}
Like others have mentioned, you need to recalculate the total every time any of select control value changes. Here's a demo (un-optimized):
document.querySelectorAll('select').forEach(select => select.addEventListener('change', (event) => {
if (allValid()) {
document.querySelector('#tally').innerHTML = calcTotal();
}
}))
const allValid = () => {
let status = true;
document.querySelectorAll('select').forEach(select => {
if (select.selectedIndex === 0) status = false;
})
return status;
}
const calcTotal = () => {
let total = 0;
document.querySelectorAll('select').forEach(select => {
total += parseInt(select.value);
})
return total;
}
<select class="select0 selectables" id="dropdown-0" name="dropdown0">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="10">Choice 1 (+10)</option>
<option value="-5">Choice 2 (-5)</option>
<option value="60">Choice 3 (+60)</option>
</select>
<br />
<select class="select1 selectables" id="dropdown-1" name="dropdown1">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="8">Choice A (+8)</option>
<option value="-10">Choice B (-10)</option>
<option value="15">Choice C (+15)</option>
</select>
<br />
<select class="select2 selectables" id="dropdown-2" name="dropdown2">
<option disabled="disabled" selected="selected" value="">select</option>
<option value="5">Choice ii (+5)</option>
<option value="15">Choice ii (+15)</option>
<option value="12">Choice iii (+12)</option>
</select>
<div id="tally" style="">0</div>

Toggle Number of Date Pickers with Dropdown list

I have a small dropdown list of numbers from 0 to 4 (I could add more), e.g. number 4 is 4 years worth of data.
If I choose 4, I get 4 rows of date pickers for the user to choose a start and end date.
It uses a for loop, and works, but the problem is I can't redo the number of date pickers with the dropdown menu.
Here is my code. Note I'm using Python Flask, hence the form action="{{url_for.."
otherwise it would be form aciton = "some url link.."
<!DOCTYPE html>
<html>
<head>
<title>Dates</title>
</head>
<body>
<form action="{{url_for('home')}}">
<ul id = "loop-list">
</ul>
<input type="submit">
</form>
<select>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Change value of the select to show the value.
<p>
</p>
<script type="text/javascript">
var res = document.querySelector("p");
var select = document.querySelector("select");
var length;
var loopList = document.getElementById("loop-list");
var unselect = document.getElementById("loop-list");
res.textContent = "Selected Value: " + select.value;
var boolean = false;
var currentSelect;
select.addEventListener("change", function(e){
res.textContent = "Selected Value: " + select.value;
currentSelect = select.value;
length = parseInt(select.value);
if(boolean == false & length !=0){
for(var i =0; i < length; i++){
loopList.innerHTML += "<li>Date " + (i+1) +
" <input type='date' name='bday' max='2018-10-01'>Enter a date<input type='date' name='bday' min='2019-12-31'></li><br>";
}
boolean = true;
}
});
unselect.addEventListener("change", function(w){
res.textContent = "Selected Value: " + unselect.value;
length = parseInt(unselect.value);
if(boolean == true & length != 0){
for(var i = 0; i < length; i++){
loopList.innerHTML -="<li>Date " + (i+1) +
" <input type='date' name='bday' max='2018-10-01'>Enter a date<input type='date' name='bday' min='2019-12-31'></li><br>";
}
boolean = false;
}
});
</script>
</body>
</html>
So if I have 4 rows of date pickers; start and end dates, respectively, how can I essentially toggle it to only displaying 3,2, 1 or 0 rows of date pickers by reusing the dropdown menu?
Hope I've worded my question properly. Any help would be greatly appreciated. I'm sure it's something relatively simple.
You could drop the unselect.addEventListener("change"... but that is there to stop the dropdown menu/list from displaying more than the maximum number of 4 rows of date pickers.
You do not need 2 listeners for this. What you can do is, reset your HTML on change and add the selected number of date pickers.
var res = document.querySelector("p");
var select = document.querySelector("select");
var loopList = document.getElementById("loop-list");
res.textContent = "Selected Value: " + select.value;
select.addEventListener("change", function(e) {
res.textContent = "Selected Value: " + select.value;
var length = parseInt(select.value);
loopList.innerHTML = ""; //Reset the HTML tag where date pickers will be added
if (length != 0) {
for (var i = 0; i < length; i++) {
loopList.innerHTML += "<li>Date " + (i + 1) +
" <input type='date' name='bday' max='2018-10-01'>Enter a date<input type='date' name='bday' min='2019-12-31'></li><br>";
}
}
});
<form>
<ul id="loop-list"></ul>
<input type="submit">
</form>
<select>
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
Change value of the select to show the value.
<p></p>

How do I remove old options in Jquery when parent select box is changed?

I have 3 chained select boxes using jquery and json.
Depending on first 2 values I filter third one my code actually works but the problem is when I change values of first 2 select boxes third select recieves new datas while keeping old ones.
I've tried to empty my array but it didn't work.
$(document).ready(function() {
var json = JSON.parse(jsonString);
var makesArray = [];
var selectedyear;
var selectedcourse;
var $yearDropDown = $("#DropDown_Year");
var $course_type = $("#course_type");
$yearDropDown.change(function() {
selectedyear = this.value;
//filter based on selected year.
});
$course_type.change(function(){
selectedcourse = this.value;
makesArray = jQuery.grep(json, function(course, i) {
return course.course_type == selectedcourse && course.year_code == selectedyear;
})
var selectBox = document.getElementById('DropDown_Make');
for(var i = 0, l = makesArray.length; i < l; i++){
var option = makesArray[i];
selectBox.options.add( new Option(option.course_code, option.course_code, option.course_code) );
}
makesArray= []; //makesArray.empty();
});
});
<div id="DrpDwn">
Year:
<select id="DropDown_Year">
<option>Yıl</option>
<option value="15">2015-2016</option>
<option value="16">2016-2017</option>
</select>
<select class="form-control" id="course_type" name="course_type" required>
<option value="" selected> Choose</option>
<option value="Yos">YÖS</option>
<option value="SatMatGeo">SAT (MAT)</option>
<option value="SatCriRea">SAT (ENG)</option>
<option value="TomerABC">TÖMER (ABC)</option>
<option value="TomerAB">TÖMER (AB)</option>
<option value="TomerBC">TÖMER (BC)</option>
<option value="TomerA1A2">TÖMER (A)</option>
<option value="TomerB1B2">TÖMER (B)</option>
<option value="TomerC1C2">TÖMER (C)</option>
</select>
Make:
<select id="DropDown_Make">
<option>None</option>
</select>
</div>
and this is JSFIDDLE
https://jsfiddle.net/rw7cb8c5/25/
Make DropDown_Make empty using selectBox.innerHTML = "" in $course_type.change() like following.
$course_type.change(function () {
selectedcourse = this.value;
makesArray = jQuery.grep(json, function (course, i) {
return course.course_type == selectedcourse && course.year_code == selectedyear;
})
var selectBox = document.getElementById('DropDown_Make');
selectBox.innerHTML = ""; //added this line
for (var i = 0, l = makesArray.length; i < l; i++) {
var option = makesArray[i];
selectBox.options.add(new Option(option.course_code, option.course_code, option.course_code));
}
makesArray.empty();
});
UPDATED FIDDLE

javascript - calculate on change of values

In my html file I have 2select boxes and 4 input text boxes.
From the first select you can choose how many numbers (textboxes) would you like to use.
From the second select you can choose a mathematical operation (+,-,*,/)
According to users choice in first select, number of input boxes will appear.
Now you add numbers to these inputs and based on what you have selected and what you have in inputs, the result should appear in a particular div.
Then, when I change anything the result should be updated.
This is what I have so far:
First select:
<select id="quantity" name="qua" onchange="selectQuantity(this.value)">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
first select js:
function selectQuantity(selectedValue){
var e = document.getElementById("quantity");
var quantity = e.options[e.selectedIndex].value;
if ( quantity==='1') {
$('#nt').fadeIn();
} else if ( quantity==='2') {
$('#nt').fadeIn();
$('#nt1').fadeIn();
} else if ( quantity==='3') {
$('#nt').fadeIn();
$('#nt1').fadeIn();
$('#nt2').fadeIn();
} else {
$('#nt').fadeIn();
$('#nt1').fadeIn();
$('#nt2').fadeIn();
$('#nt3').fadeIn()
}
}
Second select html:
<select id="operation" name="ope" onchange="selectOperation(this.value)">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
Second select js:
function selectOperation(selectedValue){
var e = document.getElementById("operation");
var operation = e.options[e.selectedIndex].value;
}
Input text example:
<input type="text" id="nt" onchange="checkField(this.value)">
js:
function checkField(val)
{
}
And the result div:
<div id="result"></div>
So, where and how should I put my calculations to achieve this dynamicly updated result? To a separate function?
All of my js functions are in separate js file.
Thank you.
-FIDDLE example
Here is a suggestion:
function calculator() {
var val1 = parseInt($('#quantity').val());
var op = $('#operation').val();
for (var i = 0; i < val1; i++) {
var incr = i ? i : '';
$('#nt' + incr).fadeIn();
}
var sum = 0;
function values2() {
var internalSum = 0;
$('[id^="nt"').each(function () {
internalSum += parseInt(this.value == '' ? 0 : this.value);
});
return internalSum;
}
switch (op) {
case '+':
sum = val1 + values2();
break;
case '-':
sum = val1 - values2();
break;
case '*':
sum = val1 * values2();
break;
case '/':
sum = val1 / values2();
break;
default:
console.log('Missing parameters');
}
$('#result').html(sum);
}
$('select, input').on('change', calculator);
Demo

Categories

Resources