Unable to fectch dataset numerical value - javascript

<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>

Related

How to change multiple dropdown selects key and values upon changing language using jQuery

i want to be able to change the value of multiple selects options based on language selector. I managed to this the long way. The following code works.
HTML
<button ID="lSel" type="button">English</button><br><br>
<label for="mySel1">Test</label>
<select name="mySelName" id="mySel1">
<option value="i0">-Mumble jumble-</option>
<option value="i1">Arigato1 satu</option>
<option value="i2">Arigato1 dua</option>
</select>
<label for="mySel2">Test</label>
<select name="mySelName" id="mySel2">
<option value="i0">-Mumble jumble-</option>
<option value="i1">Arigato2 satu</option>
<option value="i2">Arigato2 dua</option>
</select>
<label for="mySe3l">Test</label>
Script:
$(function () {
var sV01_ID1 = {"i00": "-Mumble jumble-","i01": "Arigato1 1","i02": "Arigato1 2"};
var sV01_EN1 = {"e00": "-Please Choose-","e01": "Choice1 1","e02": "Choice1 2"};
var sV01_ID2 = {"i00": "-Mumble jumble-","i01": "Arigato2 1","i02": "Arigato2 2"};
var sV01_EN2 = {"e00": "-Please Choose-","e01": "Choice2 1","e02": "Choice2 2"};
var e1 = $("#mySel1");
var e2 = $("#mySel2");
$('#lSel').click(function () {
var a = $(this);
if (a.text() == "English") {
//change the language button label
a.text('Alien');
//first remove current options
e1[0].options.length = 0;
e2[0].options.length = 0;
//now append the value for each
$.each(sV01_EN1, function (key, value) {e1.append($('<option>', {value: key}).text(value));});
$.each(sV01_EN2, function (key, value) {e2.append($('<option>', {value: key}).text(value));});
} else {
//change the language button label
a.text('English');
//first remove current options
e1[0].options.length = 0;
e2[0].options.length = 0;
//now append the value for each
$.each(sV01_ID1, function (key, value) {e1.append($('<option>', {value: key}).text(value));});
$.each(sV01_ID2, function (key, value) {e2.append($('<option>', {value: key}).text(value));});
}
});
});
Is there a way to simplify multiple e1[0].options.length = 0; and $.each(sV01_EN1, function (key, value) {e1.append($('<option>', {value: key}).text(value));});?
The only thing that changes is the assigned .text() and first argument passed to $.each, which you can do concisely with the conditional operator:
var a = $(this);
const eng = a.text() == "English";
//change the language button label
a.text(eng ? 'Alien' : 'English');
//first remove current options
e1[0].options.length = 0;
e2[0].options.length = 0;
//now append the value for each
$.each(eng ? sV01_EN1 : sV01_ID1, function (key, value) {e1.append($('<option>', {value: key}).text(value));});
$.each(eng ? sV01_EN2 : sV01_ID2, function (key, value) {e2.append($('<option>', {value: key}).text(value));});
It would make more sense to organize your data structure so that you can use dynamic property lookup with bracket notation instead of having multiple independent variable names, and also use an array instead, so you can loop over it and the selects instead of hard-coding them:
const data = {
English: [
{"e00": "-Please Choose-","e01": "Choice1 1","e02": "Choice1 2"},
{"e00": "-Please Choose-","e01": "Choice2 1","e02": "Choice2 2"}
],
Alien: [
{"i00": "-Mumble jumble-","i01": "Arigato1 1","i02": "Arigato1 2"},
{"i00": "-Mumble jumble-","i01": "Arigato2 1","i02": "Arigato2 2"}
]
};
const selects = [...$('select[name="mySelName"]')];
$('#lSel').click(function () {
const a = $(this);
const newText = a.text() === "English" ? 'Alien' : 'English';
//change the language button label
a.text(newText);
//first remove current options
for (const select of selects) {
select.options.length = 0;
}
//now append the value for each
const thisLanguageArr = data[newText];
selects.forEach((select, i) => {
for (const [key, value] of Object.entries(thisLanguageArr[i])) {
$(select).append($('<option>', {value: key}).text(value));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button ID="lSel" type="button">English</button><br><br>
<label for="mySel1">Test</label>
<select name="mySelName" id="mySel1">
<option value="i0">-Mumble jumble-</option>
<option value="i1">Arigato1 satu</option>
<option value="i2">Arigato1 dua</option>
</select>
<label for="mySel2">Test</label>
<select name="mySelName" id="mySel2">
<option value="i0">-Mumble jumble-</option>
<option value="i1">Arigato2 satu</option>
<option value="i2">Arigato2 dua</option>
</select>
<label for="mySe3l">Test</label>

Change var depending on dropdown list index item JS

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.

Javascript iteration with thymeleaf, how to pass index to array in thymeleaf

I'm setting 2 select in html, the second one depends of the first one, so I use a script "onchange", so when the first value of the select change, the second one change too, I don't know how to get the variable of my FOR to get the index of the thymeleaf model in my script
SCRIPT-
So my problem here it's inside the if when I tried to get the value of documentos[i].proyecto.id, but I can get documentos[0, 1 or any number].proyecto.id
/*<![CDATA[*/
function load(){
var e = document.getElementById("proyecto-id");
var value = e.options[e.selectedIndex].value;
var sub = document.getElementById("documento-id");
var length = sub.options.length;
for (z = 0; z < length; z++) {
sub.options[z] = null;
}
for(i=0;i<[[${#lists.size(documentos)}]];i++){
if([[${documentos[ i ].proyecto.id}]] == value){
var opt = document.createElement('option');
opt.value = [[${documentos[ i ].id}]]
opt.text = [[${documentos[ i ].nombre}]];
sub.add(opt);
}
}
}
/*]]>*/
HTML select
<select id="proyecto-id" class="custom-select" th:onchange="load()">
<option th:each="p : ${proyectos}"
th:text="${p.nombre}"
th:value="${p.id}">
</option>
</select>
<select id="documento-id" class="custom-select">
</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.

Categories

Resources