Change Select option based on input field dynamically while typing - javascript

I have an input field and a select field in my project. I would like to change the select option dynamically, based on what the user is typing (a combination of letters and numbers). The user can also select it himself, the dynamic change is sort of a helper.
<input id="userInput" type="text" class="form-control" placeholder="Type here">
<select id="sel" class="form-control form-control-xl">
<option selected>Choose one</option>
<option value="1">Dog</option>
<option value="2">Cat</option>
<option value="3">Lizard</option>
<option value="4">Fish</option>
</select>
The option is based on logic like so
var userInput = document.getElementById('userInput').value;
var sel = document.getElementById('sel');
if (userInput firstletter is Z and followed by numbers) {
$('#sel').val('1').change(); // Dog
} else if (userInput beginsWith === AB and endsWith === YZ with numbers between) {
$('#sel').val('2').change(); // Cat
} else if (userInput endsWith === XX) {
$('#sel').val('3').change(); // Lizard
} else if (userInput beginsWith === 222) {
$('#sel').val('4').change(); // Fish
}
What is the correct way to change the option similarly to a search field with autosuggest?

You can create a regex for each of your pattern as a dictionary. Then you can loop and match it when the textbox value change.
var dict = []; // create an empty array
window.onload = function(){
dict.push({key: "1", value: "^z+[0-9]*$"}); //firstletter is Z and followed by numbers
dict.push({key: "2", value: "^AB.[0-9]*YZ$"}); //beginsWith === AB and endsWith === YZ with numbers between
dict.push({key: "3", value: "^Cat$"});
dict.push({key: "4", value: "^Lizard$"});
dict.push({key: "5", value: "^Fish$"});
}
function test()
{
var userInput = document.getElementById('userInput').value;
var sel= document.getElementById('sel');
sel.value = "";
var isMatched = false;
for(var i = 0; i < dict.length; i++)
{
var reg = eval("/" + dict[i].value + "/gi");
isMatched = reg.test(userInput);
console.log(i + " " +userInput + " " + isMatched + " Key: " + dict[i].key);
if (isMatched)
{
sel.value = dict[i].key;
break;
}
}
}
<input id="userInput" type="text" class="form-control" placeholder="Type here" onchange="test()" onchange="test()">
<select id="sel" class="form-control form-control-xl">
<option value="" selected>Choose one</option>
<option value="1">First Letter Z and then numbers</option>
<option value="2">Begins with AB and number in between adn ends with YZ</option>
<option value="3">Cat</option>
<option value="4">Lizard</option>
<option value="5">Fish</option>
</select>

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>

reset a drop down list value to previous value

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

Cannot use text in option value with keyup function

I want be able to capture to name=formdesc an option value that is text and not numbers, but I need numbers to calculate price point below. Is there a way to change it, so that it calculates properly (below JS) and capture option values as text only instead numbers (HTML)?
Sample of what I need:
<select id="apparelType" name="formdesc">
<option selected="selected" value="na">Select</option>
<option value="tshirt">T-Shirt</option>
BUT Breakes my JS!
HTML: (what I have now)
<select id="apparelType" name="formdesc">
<option selected="selected" value="na">Select</option>
<option value="0">T-Shirt</option>
<option value="1">Shorts</option>
<option value="2">Hat</option>
<option value="3">Bag</option>
</select>
<input id="numb" type="number" name="formterm">
<id="tot"><Total: $0.00 >
JS:
<script type="text/javascript">// <![CDATA[
//
$(document).ready(function(){
$('#numb').keyup(function(){
var appVal = new Array();
appVal[0] = 15; <--[tshirt]
appVal[1] = 20;
appVal[2] = 25;
appVal[3] = 30;
var cost = 0;
var fmapVal = $('#apparelType').val();
if (fmapVal == 'na')
{ alert ('Please select an apparel type.');
}
else
{
cost = appVal[fmapVal];
};
//alert(cost);
var getNumb = $('#numb').val();
var baseTotal = cost * getNumb;
var getTax = baseTotal * .06;
var getTotal = baseTotal + getTax;
$('#tot').html('Total: $' + getTotal.toFixed(2));
$('#formbal').val(getTotal.toFixed(2));
});
});
// ]]></script>
<form>
<select id="apparelType" name="apparelType">
<option selected="selected" value="na">Select</option>
<option value="0">T-Shirt</option>
<option value="1">Shorts</option>
<option value="2">Hat</option>
<option value="3">Bag</option>
</select>
<label for="numb">Total: <span>$</span></label>
<input id="numb" type="number" name="formterm" value="0.00" >
<input id="pretaxTotal" type="hidden" value="0.00" >
<br>
<textarea id="formdesc" name="formdesc" rows="12" cols="20"></textarea>
</form>
<script type="text/javascript">
$('#apparelType').change(function(){
var apparelType = $('#apparelType');
var fmapVal = apparelType.val();
if (fmapVal == 'na') {
alert('Please select an apparel type.');
} else {
var appVal = [ 15, 20, 25, 30 ];
var description = apparelType.find('option:selected').text();
var cost = appVal[fmapVal];
var pretaxTotal = parseInt($('#pretaxTotal').val());
var subtotal = pretaxTotal + cost;
var updatedTotal = ( subtotal * 1.06 ).toFixed(2);
$('#pretaxTotal').val(subtotal);
$('#numb').val(updatedTotal);
$('#formdesc').append(description + '\n');
}
});
/* The following code is cosmetic. Makes dollar sign appear to be inside the input field */
$('label > span').css('position','relative').css('left','20px').css('font-size','80%');
$('input[type=number]').css('padding-left','15px');
</script>
If you need to take option name then val is not what you need. Instead try this:
var optionName = $('#apparelType').find('option:selected').text();
Hope I understood you correctly (although it's hard).
Could use a function with a case statement to get the cost from passed text strings:
function getVal(value) {
switch(value) {
case 'tshirt':
cost = 15;
break;
case 'shorts':
cost = 15;
break;
case 'hat':
cost = 15;
break;
case 'bag':
cost = 15;
break;
default:
cost = 'Please select an option...';
break;
}
return cost;
}
Then in your if statement use cost = getVal(fmapVal);.

Categories

Resources