Change var depending on dropdown list index item JS - javascript

I'm trying to do a loan calculator where you can stimate the monthly playment value according to diferent interest and secures.
everything is working fine now, but then I was told that my var S variable depends on the type of credit.
that beign said:
var S = Y*0.00342
BUT
if items # 0,5,6,10,16 are selected in drop down list
THEN
my var S becomes
var S = Y*0.00042
so my question is:
How can I make this 'var s' to be depending on dropdownlist items?
how do I integrate this condition inside the function?
thanks in advance! :)
EDIT: here is the HTML list --- value will be used in another var
<select id="list" >
<option value="2">Avance de nomina</option>
<option value="1.092">Calamidad</option>
<option value="1.292">Compra de vehiculo</option>
<option value="1.342">Compra de cartera</option>
<option value="1.292">Compra de moto nueva</option>
<option value="1.892">Consumo</option>
<option value="0.842">Crediaportes</option>
<option value="1.342">Cuota inicial compra vivienda nueva</option>
<option value="1.342">Educativo</option>
<option value="2.142">Electrodomestico</option>
<option value="2.042">Gerencia</option>
<option value="2.292">Ordinario con codeudor</option>
<option value="2.292">Ordinario sin codeudor</option>
<option value="1.342">Pago impuesto y reforma vivienda</option>
<option value="1.542">Prima</option>
<option value="1.942">Turismo y recreación</option>
<option value="1.892">Convenios y seguros</option>
</select>
here is the Function in Javascript
function INTERES() {
var x = document.getElementById("list").value;
var y = document.getElementById("valor").value;
var c = document.getElementById("cuotas").value;
var P = x/100;
var A = 1+P
var E = Math.pow(A, c)
var PE = P*E;
var I = E-1
var PEI = PE/I;
var T = y*PEI;
var G = document.getElementById("list").selectedIndex
var S = y*0.00042;
var payment = T+S+2000;
document.getElementById("CALCULATOR").innerHTML = formatter.format(payment.toFixed());
}
var S will be used in function like
Payment = T + S + 2000
EDIT 2:
I think im getting closer with this
var S= y*0.00342;
var G = document.getElementById("list").selectedIndex ;
if (G === ["0", "5", "6", "10", "16"]) {
S = y*0.00042;
}
maybe I have a syntaxis error? Im not sure how to proceed but would this work?

Try:
var S = Y*0.00342
if ([0,5,6,10,16].includes(document.getElementById("list").selectedIndex)) {
var S = Y*0.00042
}
Regardless of what you do, always make sure you sanitize anything you get from the DOM to maintain security.

Related

Unable to fectch dataset numerical value

<select class="license_type" name="license_type" id="license_type">
<option value="l_one" data-one="500">License 1</option>
<option value="l_two" data-two="700">License 2</option>
<option value="l_three" data-three="1400">License 3</option>
</select>
These 500, 700, 1400 will later come programmatically through PHP. So my goal is to fetch them in JS through the dataset.
The JS function that I wrote is:
function someFunction() {
var vOne= document.getElementById("license_type");
var vTow = vOne.options;
var c1 = vTow.dataset.one;
var c2 = vTow.dataset.two;
var c3 = vTow.dataset.three;
}
then in another JS instead of the hard coded prices like this :
var prices = [500, 700, 1400];
and this:
var prices = ['c1', 'c2', 'c3'];
But this generates NAN that means c1, c2, c3 doesn't have numerical values.
whats the Fix?
Looking at your code it seems that it has three static options, so considering that below code will work.
function someFunction() {
var license_type= document.getElementById("license_type");
var c1 = license_type.options[0].getAttribute('data-one');
var c2 = license_type.options[1].getAttribute('data-two');
var c3 = license_type.options[2].getAttribute('data-three');
var prices = [c1, c2, c3];
console.log(prices)
}
But if the options are dynamic than you'll have to loop through the options.
You should use getAttribute and parseInt. Also loop through the options, and use destructuring like so:
function someFunction() {
var vOne = document.getElementById("license_type");
var options = vOne.getElementsByTagName("option");
var [c1, c2, c3] = options.map(e => e.getAttribute("data-one"));
}
First, I will use querySelectorAll() to get all options of the target select. Then, I will use Array::map() to map all options to his data-* attribute. Note I have to get the second part of the name of data-* attribute from the value attribute, because the data-* attribute appears to be related to the value attribute (is not an uniform name):
var prices;
function someFunction()
{
var opts = document.querySelectorAll("#license_type option");
prices = Object.values(opts).map(o =>
{
let token = o.getAttribute("value").match(/l_(\w+)/)[1];
return o.getAttribute("data-" + token);
});
console.log(prices);
}
someFunction();
<select class="license_type" name="license_type" id="license_type">
<option value="l_one" data-one="500">License 1</option>
<option value="l_two" data-two="700">License 2</option>
<option value="l_three" data-three="1400">License 3</option>
</select>

Change options in a drop-down list depending on another selected drop-down list

I'm trying to do this which you have a dropdown list and depending what you select, the next dropdown list will have different options.
I have my codes in jsfiddle
<!DOCTYPE html>
<html>
<body>
<select id="diffList" onchange="changeList()">
<option value="">-- Difficulty --</option>
<option value="1">Easy</option>
<option value="2">Medium</option>
<option value="3">Difficult</option>
</select>
<select id="numbList"></select>
<script>
var difficulty = {};
difficulty['1'] = [1,2,3];
difficulty['2'] = [4,5,6];
difficulty['3'] = [7,8,9];
function changeList() {
var diffList = document.getElementById("diffList");
var numbRange = document.getElementById("numbList");
var selectDiff = diffList.options[diffList.selectIndex].value;
while(numbRange.options.length)
{
numbRange.remove(0);
}
var diff = difficulty[selectDiff];
if(diff)
{
var i;
for(i = 0; i < diff.length; i++)
{
var difficulty = new Option(diff[i], i);
numbRange.options.add(difficulty);
}
}
}
</script>
</body>
</html>
The problem I'm encountering is the next droplist is not showing any options. I've look through my codes many times and I still can't seem to find out what's wrong with it. Would someone mind looking over it and let me know?
Thanks a lot.
Here is working code (tested only ib Chrome).
The one problem was here - for loop does not create nested scope in JS, so it shadowed global variable difficulty
for(i = 0; i < diff.length; i++) {
var difficulty = new Option(diff[i], i);
...
Ok, let's do it:
You should not use onchange="changeList()" on jsfiddle beause it wraps your code into the onclick handler and the changeList function does not visible from the outer scope.
You should use diffList.value for detect the currently selected value in the first selectbox: var selectDiff = diffList.value;
Do not name the new option variable difficulty - it overrides the difficulty variable from the outer scope. Name it option, for example: var option = new Option(diff[i], i);
Add the event listener for diffList from JS: diffList.addEventListener('change', changeList)
http://jsfiddle.net/h3hbovar/4/
I think the primary problem here was javascript scoping within functions. If difficulty is defined outside the context of the function, it needs to be defined as a global by being attached to window
<!DOCTYPE html>
<html>
<body>
<select id="diffList" onchange="changeList()">
<option value="">-- Difficulty --</option>
<option value="1">Easy</option>
<option value="2">Medium</option>
<option value="3">Difficult</option>
</select>
<select id="numbList"></select>
<script>
window.difficulty = {};
window.difficulty['1'] = [1,2,3];
window.difficulty['2'] = [4,5,6];
window.difficulty['3'] = [7,8,9];
function changeList() {
var diffList = document.getElementById("diffList");
var numbRange = document.getElementById("numbList");
var selectDiff = diffList.options[diffList.selectedIndex].value;
while(numbRange.options.length)
{
numbRange.remove(0);
}
var diff = window.difficulty[selectDiff];
if(diff)
{
var i;
for(i = 0; i < diff.length; i++)
{
var difficulty = new Option(diff[i], i);
numbRange.options.add(difficulty);
}
}
}
</script>
</body>
</html>

I have two onchange methods and two values I need to pass

function changeHiddenInput(cLeague, nLeague) {
console.log(cLeague);
console.log(nLeague);
var objHidden1 = document.getElementById("hiddenInput1");
var objHidden2 = document.getElementById("hiddenInput2");
objHidden1.value = cLeague.value;
objHidden2.value = nLeague.value;
var a = objHidden1.value;
var b = objHidden1.value;
result.innerHTML = a + b;
}
<select class="form-control" id="currentleague" onchange="document.getElementById('currentleague').src=this.value; changeHiddenInput(select)">
<option value="rankicons/bronze5.png" (another value goes somewhere in here)>Bronze V</option>
</select>
Basically the first onchange changes the image in value, the second onchange passes in a value and does some math. Is there an alternative I could use to value or could I somehow pass in two values and somehow tell them apart?
You can have 2 values within the value property:
<option value="rankicons/bronze5.png,value nr 2">...</option>
Sample:
function changeHiddenInput(league) {
var league_values = league.split(",");
var objHidden1 = document.getElementById("hiddenInput1");
var objHidden2 = document.getElementById("hiddenInput2");
objHidden1.value = league_values[0];
objHidden2.value = league_values[1];
var a = objHidden1.value;
var b = objHidden1.value;
result.innerHTML = a + b;
// remove comment and set uniqe id to set img element src
//document.getElementById('img_id').src=league_values[0];
}
HTML:
<select class="form-control" id="currentleague" onchange="changeHiddenInput(this.options[this.selectedIndex].value)">
<option value="rankicons/bronze5.png,value nr 2">...</option>
</select>
The value document.getElementById('currentleague').src=this.value; I removed as it referenced the select element itself (same id) and added it to your function instead.

How to pull form variables from cookies based on drop down selection in JS

I have the following code that when a user selects from a drop down, the selectedIndex is used to refer to the corresponding array (var varNames0, var varNames1, etc) of form field variables stored in a browser cookie. When the user clicks the edit button, the correct form values should display, along with their values set by the user.
How do I go about pulling the form values correctly, based on the following code. I am almost there, but only seeing the first letter of each array value, and the location in the array is displayed at the bottom of the form that pops up.
Edit Vars
<select id="product" name="product" >
<option value="prod1" selected>Prod 1</option>
<option value="prod2" >Prod 2</option>
<option value="prod3" >Prod 3</option>
<option value="prod4" >Prod 4</option>
</select>
var varNames0 = [
"property1",
"property2",
"top",
"property3",
"property4",
"closeBtn",
"loadingText",
"property5"];
var editableVars = function(){
var html = "";
var varNames = "varNames" + document.getElementById("product").selectedIndex;
for(var i in varNames){
html += "<p><label for="+varNames[i]+">"+varNames[i]+":</label> <input type=\"text\" id=\""+varNames[i]+"\" placeholder=\"enter "+varNames[i]+"...\" value=\""+socialVars[varNames[i]]+"\" /></p>";
}
How about making it a little easier on yourself, if possible, and structuring things like this:
var varNames = [
[
"property1",
"property2",
"top",
"property3",
"property4",
"closeBtn",
"loadingText",
"property5"
]
];
var editableVars = function(){
var html = "";
var data = varNames[document.getElementById("product").selectedIndex];
for(var i in data){
html += "<p><label for="+data[i]+">"+data[i]+":</label> <input type=\"text\" id=\""+data[i]+"\" placeholder=\"enter "+data[i]+"...\" value=\""+socialVars[data[i]]+"\" /></p>";
}
The key was to use switch statements:
var varNames;
switch(document.getElementById("product").selectedIndex)
{
case 0:
varNames = varNames0
break;
case 1:
varNames = varNames1
break;
case 2:
varNames = varNames2
break;
case 3:
varNames = varNames3
break;
}

javascript code doesn't work in IE8

i have two drop-down menus. On the selection of one menu the value of other changes. But in IE it doesn't work and my drop-down appears empty. here is my code
<div style="position:absolute; bottom:95px; right:631px;">
<select id='Country' name='Country' style="width: 148px;background-color:white;">
<option selected='selected'>All Countries</option>
<option>Australia</option>
<option>Cambodia</option>
<option>China</option>
<option>India</option>
<option>Indonesia</option>
<option>Hong Kong</option>
</select>
<select id='Airport' name='Airport' style="width: 148px;background-color:white;"></select>
</div>
JavaScript code
<script type="text/javascript">
(function(){
var bOptions = {"All Countries":["All Airports"], "Australia":["Sydney","Brisbane","Melbourne","Perth"], "Cambodia":["Phnom Penh"], "China":["Beijing","Guangzhou","Hangzhou","Kunmimg","Shanghai Pudong","Shanghai Hongqiao"],
"India":["Bangalore","Mumbai","Delhi"],"Indonesia":["Jakarta","Bali"],"Hong Kong":["Hong Kong"],"Japan":["Osaka","Narita","Haneda"],"Korea":["Seoul Gimpo","Seoul Incheon"],
"Macau":["Macau"],"Malaysia":["Kuala Lumpur"],"New Zealand":["Auckland"],"Philippines":["Manila"],"Singapore":["Singapore"],"Taiwan":["Taipei","Kaohsiung","Songshan"],"Thailand":["Bangkok","Phuket"],
"Vietnam":["Hanoi","Ho Chi Minh City"]};
var A = document.getElementById('Country');
var B = document.getElementById('Airport');
//on change is a good event for this because you are guarenteed the value is different
A.onchange = function(){
//clear out B
B.length = 0;
//get the selected value from A
var _val = this.options[this.selectedIndex].value;
//loop through bOption at the selected value
for ( var i in bOptions[_val]){
//create option tag
var op = document.createElement('option');
//set its value
op.value = bOptions[_val][i];
//set the display label
op.text = bOptions[_val][i];
//append it to B
B.appendChild(op);
}
};
//fire this to update B on load
A.onchange();
})();
</script>
anyone help?
Try to use op.innerText = bOptions[_val][i]; for old versions of IE because it doesn't supports op.text
Change your code like,
if(IE8)// use user_agent to get browser version and browser type
{
op.innerText = bOptions[_val][i];
}
else
{
op.text = bOptions[_val][i];
}
Read browser compalibilty and innerText
Here is a link which will sove your problem : http://jehiah.cz/a/firing-javascript-events-properly

Categories

Resources