could somebody tell me how to pass values from form to 2d associative array? I made simple associative array and it was easy to write it, but now I have problem with 2d array and getSalary() function. getWorkload() works fine, but getSalary() doesn't work. I would be grateful for some tip or code modification.
var salaries = [
[
"mrWh", ["intern", 2511],
["contractual", 2592],
["designated", 2932],
["certificated", 3411]
],
[
"mrbchWht", ["intern", 2121],
["contractual", 2200],
["designated", 2522],
["certificated", 3000]
],
[
"bchWht", ["intern", 1868],
["contractual", 1910],
["designated", 2200],
["certificated", 2600]
]
];
var worklooad = [];
worklooad["20"] = 20;
worklooad["25"] = 25;
worklooad["30"] = 30;
worklooad["35"] = 35;
function getSalary() {
var slr = 0;
var formData = document.forms["data"];
var selEdLvl = formData.elements["edLvl"];
var selDegree = formData.elements["degrees"];
slr = salaries[selEdLvl][selDegree.value];
return slr;
}
function getWorkload() {
var psm = 0;
var formularz = document.forms["data"];
var selPsm = formularz.elements["workload"];
psm = worklooad[selPsm.value];
return psm;
}
function chkEtat(pStr) {
var spl44 = document.getElementById("spl44");
if (!isNaN(pStr) && pStr !== "" && pStr <= getWorkload()) {
spl44.style.fontSize = "22px";
pStr = pStr / getWorkload();
spl44.innerHTML = pStr.toFixed(2) + "<br>";
return pStr;
} else if (isNaN(pStr)) {
spl44.style.fontSize = "18px";
spl44.innerHTML = "Enter number." + "<br>";
return 0;
} else if (pStr > getWorkload()) {
var spl44 = document.getElementById("spl44");
spl44.innerHTML = "inappropriate value." + "<br>";
return 0;
} else {
document.getElementById("spl44").innerHTML = "";
}
}
function calcpTime() {
var str = document.getElementById("inppn");
var vStr = document.getElementById("inppn").value;
var rpvStr = vStr.replace(/,/g, '.');
rpvStr = parseFloat(rpvStr);
var cmp = /^\d{1,2}$/.test(vStr);
if (cmp === true) {
var nStr = vStr.concat(".0");
document.getElementById("inppn").value = nStr;
var fnStr = parseFloat(nStr);
return chkEtat(fnStr);
}
return chkEtat(rpvStr);
}
function calcSalaries() {
calcpTime();
document.getElementById("spl55").innerHTML = getSalary() * calcpTime();
}
function clearInps() {
document.getElementById("data").reset();
}
<form id="data">
<div>
<label>Education level: </label>
<select id="edLvl">
<option value="" selected disabled hidden>Select</option>
<option value="mrWh">Master with pedagogical preparation</option>
<option value="mrbchWht">Master without pedagogical preparation</option>
<option value="mrbchWht">Bachelor with pedagogical preparation</option>
<option value="bchWht">Bachelor without pedagogical preparation</option>
</select>
</div>
<div>
<label>Ascension degree: </label>
<select id="degrees">
<option value="" selected disabled hidden>Select</option>
<option value="intern">intern</option>
<option value="contractual">contractual</option>
<option value="designated">designated</option>
<option value="certificated">certificated</option>
</select>
</div>
<div>
<label>Workload: </label>
<select id="workload">
<option value="" selected disabled hidden>Select</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
</select>
</div>
<div>
<label>Workload: </label>
<input onchange="calcSalaries()" type=text id="inppn">
<span id="spl44"></span>
</div>
<div>
<label>Salary: </label>
<span id="spl55"></span>
</div>
<button id="clear" onclick="clearInps()">Clear data</button>
</form>
Use .find to identify particular elements in an array:
var salaries = [
[
"mrWh", ["intern", 2511],
["contractual", 2592],
["designated", 2932],
["certificated", 3411]
],
[
"mrbchWht", ["intern", 2121],
["contractual", 2200],
["designated", 2522],
["certificated", 3000]
],
[
"bchWht", ["intern", 1868],
["contractual", 1910],
["designated", 2200],
["certificated", 2600]
]
];
document.querySelector('#data').addEventListener('submit', e => e.preventDefault());
function getSalary() {
const edLvlVal = document.querySelector('#edLvl').value;
const degreeVal = document.querySelector('#degrees').value;
const salary = salaries
.find(([level]) => level === edLvlVal)
.find(([degree]) => degree === degreeVal);
console.log('salary ' + salary);
}
<form id="data">
<div>
<label>Education level: </label>
<select id="edLvl">
<option value="" selected disabled hidden>Select</option>
<option value="mrWh">Master with pedagogical preparation</option>
<option value="mrbchWht">Master without pedagogical preparation</option>
<option value="mrbchWht">Bachelor with pedagogical preparation</option>
<option value="bchWht">Bachelor without pedagogical preparation</option>
</select>
</div>
<div>
<label>Ascension degree: </label>
<select id="degrees">
<option value="" selected disabled hidden>Select</option>
<option value="intern">intern</option>
<option value="contractual">contractual</option>
<option value="designated">designated</option>
<option value="certificated">certificated</option>
</select>
</div>
<div>
<label>Workload: </label>
<select id="workload">
<option value="" selected disabled hidden>Select</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
</select>
</div>
<div>
<label>Workload: </label>
<input onchange="calcSalaries()" type=text id="inppn">
<span id="spl44"></span>
</div>
<div>
<label>Salary: </label>
<span id="spl55"></span>
</div>
<button onclick="getSalary()">Get Salary</button>
<button id="clear" onclick="clearInps()">Clear data</button>
</form>
But your data structure is very difficult to deal with - you should use an object instead, so you can access by string keys, which is much simpler than .find. Use something like this instead:
const salaries = {
mrWh:
{intern: 2511,
contractual: 2592,
designated: 2932,
certificated: 3411
},
mrbchWht: {
intern: 2121,
contractual: 2200,
designated: 2522,
certificated: 3000
},
bchWht: {
intern: 1868,
contractual: 1910,
designated: 2200,
certificated: 2600
}
};
const prop1 = 'mrWh';
const prop2 = 'designated';
console.log(salaries[prop1][prop2]);
I think your main issue is that you're missing .value in a couple of places. For example: var selEdLvl = formData.elements["edLvl"]; should probably be changed to var selEdLvl = formData.elements["edLvl"].value;
If you turn your salaries array into an "associative" one:
var salaries_assoc = salaries
.reduce(function(ac,d,i){
ac[d[0]]=d.slice(1)
.reduce(function(ac,d,i){
ac[d[0]]=d[1];return ac
},{});
return ac
},{});
/*"{
"mrWh": {
"intern": 2511,
"contractual": 2592,
"designated": 2932,
"certificated": 3411
},
"mrbchWht": {
"intern": 2121,
"contractual": 2200,
"designated": 2522,
"certificated": 3000
},
"bchWht": {
"intern": 1868,
"contractual": 1910,
"designated": 2200,
"certificated": 2600
}
}"*/
Now you can do this in your event (or in your getSalaries function etc):
var value1 = document.getElementById("edLvl").value,//"mrWh"
value2 = document.getElementById("degrees").value;//"intern"
salaries_assoc[value1] && salaries_assoc[value1][value2];//2511
Related
I'm Setup a <select> dropdown list and I trying to make options sorting in numerical order (Ascending) :
HTML
<select id="singleSelector">
<option value="/single?id=544">1</option>
<option value="/single?id=598">4</option>
<option value="/single?id=605">6</option>
<option value="/single?id=604">3</option>
<option value="/single?id=603">7</option>
<option value="/single?id=602">5</option>
<option value="/single?id=601">2</option>
</select>
Edit :
When using the following JS by #Sanjay, the order is not correct :
JavaScript :
$(function() {
// choose target dropdown
var select = $('select');
select.html(select.find('option').sort(function(x, y) {
// to change to descending order switch "<" for ">"
return $(x).text() > $(y).text() ? 1 : -1;
}));
});
Output :
It's possible to make order 1,2,3,4,5 instead of 1,10,11...,2,20,21 ?
Here is working example.
$(function() {
var select = $('select');
select.html(select.find('option').sort(function(x, y) {
var num1 = parseInt($(x).text());
var num2 = parseInt($(y).text());
return num1> num2 ? 1 : -1;
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div id="wrapper">
<select>
<option selected>Choose a number</option>
<option value="3">3</option>
<option value="1">1</option>
<option value="0">0</option>
<option value="2">2</option>
<option value="8">8</option>
</select>
</div>
try THIS
var target = document.getElementById('singleSelector');
function sortIt(target ) {
var tmp = new Array();
for (var i=0;i<target.options.length;i++) {
tmp[i] = new Array();
tmp[i][0] = target.options[i].text;
tmpA[i][1] = target.options[i].value;
}
tmp.sort();
while (target.options.length > 0) {
target.options[0] = null;
}
for (var i=0;i<tmp.length;i++) {
var op = new Option(tmp[i][0], tmp[i][1]);
target.options[i] = op;
}
return;
I've created dynamic dropdown list and I want to obtain values from selected option. Dynamic dropdown works fine but I have struggle with taking values from selected option.
For example I want to take value of avgDamage from selected object tpPrototype.
Need some help here
HTML:
<form name="myform" id="myForm">
<p>tank 1</p>
<div class="select">
<select classname="optone" id="tankSel" size="1">
<option value="" selected="selected">Tank Nation</option>
</select>
</div>
<div class="select">
<select name="opttwo" id="typeSel" size="1">
<option value="" selected="selected">Tank Type</option>
</select>
</div>
<div class="select">
<select name="optthree" id="nameSel" size="1">
<option value="" selected="selected">Tank Name</option>
</select>
</div>
</form>
JavaScript:
const tpPrototype = {
name: "50TP prototyp",
avgDamage: 440,
healthPool: 1500,
reloadTime: 13.62,
},
tpMarkowskiego = {
name: "53TP prototyp",
avgDamage: 420,
healthPool: 1450,
reloadTime: 12.18,
},
proggettoM35 = {
name: "Progetto M35 mod.46",
avgDamage: 240,
healthPool: 1400,
reloadTime: 1,
},
window.onload = function () {
let tankSel = document.getElementById("tankSel");
typeSel = document.getElementById("typeSel");
nameSel = document.getElementById("nameSel");
for (let tank in tankObject) {
tankSel.options[tankSel.options.length] = new Option(tank, tank);
}
tankSel.onchange = function () {
typeSel.length = 1;
nameSel.length = 1;
if (this.selectedIndex < 1) return;
for (let type in tankObject[this.value]) {
typeSel.options[typeSel.options.length] = new Option(type, type);
}
};
tankSel.onchange();
typeSel.onchange = function () {
nameSel.length = 1;
if (this.selectedIndex < 1) return;
let names = tankObject[tankSel.value][this.value];
for (let i = 0; i < names.length; i++) {
nameSel.options[nameSel.options.length] = new Option(names[i], names[i]);
}
};
This looks like a duplicate of question 1085801
Basically, once you have the selection object, you access the "value" attribute through:
var selectedValue = selectionObject.options[index].value;
or you can access the actual text, such as "Tank Type" in your initial HTML as:
var selectedText = selectionObject.options[index].text;
Once you have this, you should just be able to use that value/text to access your "tankObject" property:
var selectedAvgDamage = tpPrototype[selectedText];
I want to create a javascript function for the following:
<td>
<h4 class="subject-name">Construction Management</h4>
</td>
<td>
<select id="sub9Score">
<option selected value="Select Grade">Grade</option>
<option value="10">S</option>
<option value="9">A</option>
<option value="8">B</option>
<option value="7">C</option>
<option value="6">D</option>
<option value="5">E</option>
<option value="0">F</option>
</select>
</td>
Here, I want to get a selected value by user and assign the letter a value(number). Then I want to use that value for calculation and display that in an alert box. Please give me a code to assign a numerical value to user selected option. Use only javascript. No jquery
Can anyone find an error in my code here:
function calculator(){
var sub1score = document.getElementById('sub1Score');
var sub1 = sub1score.options[sub1score.selectedIndex].value;
var sub2score = document.getElementById('sub2Score');
var sub2 = sub2score.options[sub2score.selectedIndex].value;
var sub3score = document.getElementById('sub3Score');
var sub3 = sub3score.options[sub3score.selectedIndex].value;
var sub4score = document.getElementById('sub4Score');
var sub4 = sub4score.options[sub4score.selectedIndex].value;
var sub5score = document.getElementById('sub5Score');
var sub5 = sub5score.options[sub5score.selectedIndex].value;
var sub6score = document.getElementById('sub6Score');
var sub6 = sub6score.options[sub6score.selectedIndex].value;
var sub7score = document.getElementById('sub7Score');
var sub7 = sub7score.options[sub7score.selectedIndex].value;
var sub8score = document.getElementById('sub8Score');
var sub8 = sub8score.options[sub8score.selectedIndex].value;
var sub9score = document.getElementById('sub9Score');
var sub9 = sub9score.options[sub9score.selectedIndex].value;
var total = (sub1*4)+(sub2*4)+(sub3*4)+(sub4*3)+(sub5*4)+(sub6*1.5)+(sub7*1.5)+(sub8*1.5)+(sub9*4);
var gpa = total/27.5;
var final = gpa.tofixed(2);
alert('Your CGPA is '+final+'');
}
Updated my javascript function. But this isnt displaying alert box:
function calculator(){
var sub1score = document.getElementById('sub1Score');
var sub1 = sub1score.options[sub1score.selectedIndex].value;
var a = parseInt("sub1");
var sub2score = document.getElementById('sub2Score');
var sub2 = sub2score.options[sub2score.selectedIndex].value;
var b = parseInt("sub2");
var sub3score = document.getElementById('sub3Score');
var sub3 = sub3score.options[sub3score.selectedIndex].value;
var c = parseInt("sub3");
var sub4score = document.getElementById('sub4Score');
var sub4 = sub4score.options[sub4score.selectedIndex].value;
var d = parseInt("sub4");
var sub5score = document.getElementById('sub5Score');
var sub5 = sub5score.options[sub5score.selectedIndex].value;
var e = parseInt("sub5");
var sub6score = document.getElementById('sub6Score');
var sub6 = sub6score.options[sub6score.selectedIndex].value;
var f = parseInt("sub6");
var sub7score = document.getElementById('sub7Score');
var sub7 = sub7score.options[sub7score.selectedIndex].value;
var g = parseInt("sub7");
var sub8score = document.getElementById('sub8Score');
var sub8 = sub8score.options[sub8score.selectedIndex].value;
var h = parseInt("sub8");
var sub9score = document.getElementById('sub9Score');
var sub9 = sub9score.options[sub9score.selectedIndex].value;
var i = parseInt("sub9");
var total = (a*4)+(b*4)+(c*4)+(d*3)+(e*4)+(f*1.5)+(g*1.5)+(h*1.5)+(i*4);
var gpa = (total/27.5);
var final = gpa.toFixed(2);
alert('Your CGPA is '+final+'');
}
https://drive.google.com/file/d/0B_mI455BxLOWS3V0UFNaVnNEUlU/view?usp=sharing Link to my full codes
You have forgotten to use parseInt because of it. It is not performing proper operations. Please check my updated answer.
var selectElement = document.getElementById("sub9Score");
function getSelectedVlue(){
var selectValue = selectElement.options[selectElement.selectedIndex].value;
if(selectValue== "Select Grade") return;
alert("select value is: "+
selectValue);
alert("adding 1 and selected value with out parse int "+ (1 + selectValue)); alert("adding 1 and selected value with parse int "+ (1 + parseInt(selectValue)));
}
<td>
<h4 class="subject-name">Construction Management</h4>
</td>
<td>
<input type="button" value="Get Selected Value" onclick="getSelectedVlue()"> <br/><br/>
<select id="sub9Score">
<option selected value="Select Grade">Grade</option>
<option value="10">S</option>
<option value="9">A</option>
<option value="8">B</option>
<option value="7">C</option>
<option value="6">D</option>
<option value="5">E</option>
<option value="0">F</option>
</select>
</td>
If you want number then assign value to letters
function getSelectedVlue(){
var e = document.getElementById("sub9Score");
alert("you have selected : " + (e.options[e.selectedIndex].value));
}
<td>
<h4 class="subject-name">Construction Management</h4>
</td>
<td>
<input type="button" value="Get Selected Value" onclick="getSelectedVlue()"> <br/><br/>
<select id="sub9Score">
<option selected value="NA">Grade</option>
<option value="19">S</option>
<option value="1">A</option>
<option value="2">B</option>
<option value="3">C</option>
<option value="4">D</option>
<option value="5">E</option>
<option value="6">F</option>
</select>
</td>
Get the element using the ID you've already defined. Then define a handler for the change event which does something with the value property.
var sub9Score = document.getElementById('sub9Score');
sub9Score.onchange = function() {
console.log(this.value)
};
<select id="sub9Score">
<option selected value="Select Grade">Grade</option>
<option value="S">S</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
<option value="D">D</option>
<option value="E">E</option>
<option value="F">F</option>
</select>
I am using the following select form and function to select the transport type first and I would like to have a list of cars or motorcycles in the second form depending on my choice at the first stage. I will really appreciate if you can let me know why my function is not working and what I am missing
<!doctype html>
<html>
<body>
<select id="transport" name="transport">
<option value="choose">Please choose a type</option>
<option value="cars">Cars</option>
<option value="motorcycles">Motorcycles</option>
</select>
<select id="model" name="model">
<option>Please choose a type first</option>
</select>
<input id="submit" type="submit" value="submit" />
</body>
<script>
(function(){
var type = document.getElementById('transport');
var model = document.getElementById('model');
var cars = {
Alfa_Romeo: '4 C Spider',
Aston_Martin: 'V12 Vantage',
Audi: 'A4 Allroad',
Ford: 'Focus'
};
var motorcycles = {
Yamaha: 'YZF-R6',
Kawasaki: 'Versys 650 LT',
Suzuki: 'Boulevard C50',
Honda: 'Super Cub C100'
};
addEvent(type, 'change', function() {
if (this.value === 'choose'){
model.innerHTML = '<option>Please choose a type first</option>';
return;
}
var models = getModels(this.value);
var options = '<option>Please choose a model</option>';
for (var key in models){
options += '<option value="' + key + '">' + models[key] + '</option>';
}
model.innerHTML = options;
});
function getModels(transport) {
if (transport === 'cars') {
return cars;
} else if (transport === 'motorcycles'){
return motorcycles;
}
}
}());
</script>
`
Use addEventListener. Check this working snippet
(function(){
var type = document.getElementById('transport');
var model = document.getElementById('model');
var cars = {
Alfa_Romeo: '4 C Spider',
Aston_Martin: 'V12 Vantage',
Audi: 'A4 Allroad',
Ford: 'Focus'
};
var motorcycles = {
Yamaha: 'YZF-R6',
Kawasaki: 'Versys 650 LT',
Suzuki: 'Boulevard C50',
Honda: 'Super Cub C100'
};
type.addEventListener('change', function() {
if (this.value === 'choose'){
model.innerHTML = '<option>Please choose a type first</option>';
return;
}
var models = getModels(this.value);
var options = '<option>Please choose a model</option>';
for (var key in models){
options += '<option value="' + key + '">' + models[key] + '</option>';
}
model.innerHTML = options;
});
function getModels(transport) {
if (transport === 'cars')
{
return cars;
}
else if (transport === 'motorcycles'){
return motorcycles;
}
}
}());
<select id="transport" name="transport">
<option value="choose">Please choose a type</option>
<option value="cars">Cars</option>
<option value="motorcycles">Motorcycles</option>
</select>
<select id="model" name="model">
<option>Please choose a type first</option>
</select>
<input id="submit" type="submit" value="submit" />
I'm building a simple random word generator and am trying to have a <select> drop-down determine the number of words to be displayed. My idea was to have the <option>'s value contain the variables I want to be parsed into my function. However, it doesn't read the variables as I'd hoped, like it does in the first div, and instead writes the literal values. I'm sure there's a more elegant way to write this, but now I'm curious if I can even do it this way.
JSFiddle
HTML:
<select id="wordCount" class="span2">
<option value="word1">1 Words</option>
<option value="word1+' '+word2">2 Words</option>
<option value="word1+' '+word2+' '+word3">3 Words</option>
<option value="word1+' '+word2+' '+word3+' '+word4">4 Words</option>
</select>
<input id="gen" type="submit" value="Generate">
<div id="wordBin"></div>
<div id="wordBin2"></div>
JavasSript:
$('#gen').click(function generateWords(){
var wordCount = document.getElementById('wordCount').value;
var wordbank = ['rock', 'paper', 'scissor', 'apple', 'beer', 'potato'];
var word1 = wordbank[Math.floor(Math.random()*wordbank.length)];
var word2 = wordbank[Math.floor(Math.random()*wordbank.length)];
var word3 = wordbank[Math.floor(Math.random()*wordbank.length)];
var word4 = wordbank[Math.floor(Math.random()*wordbank.length)];
var wordBin = document.getElementById('wordBin');
var wordBin2 = document.getElementById('wordBin2');
wordBin.innerHTML = word1+' '+word2+' '+word3+' '+word4;
wordBin2.innerHTML = wordCount;
});
I don't recommend this at all, but what you're looking for is eval. I've updated the fiddle with a simple change:
wordBin.innerHTML = word1+' '+word2+' '+word3+' '+word4;
to
wordBin.innerHTML = eval(wordCount);
and it works just like you want. However, that's a TERRIBLE way to do things (just as you alluded to). It would be much better if you stored a count in your values and looped through the count by appending the random word. The real HTML/javascript would work like this:
HTML:
<select id="wordCount" class="span2">
<option value="1">1 Words</option>
<option value="2" selected="selected">2 Words</option>
<option value="3">3 Words</option>
<option value="4">4 Words</option>
</select>
<input id="gen" type="submit" value="Generate">
<div id="wordBin"></div>
<div id="wordBin2"></div>
JS:
$('#gen').click(function generateWords() {
var wordCount = document.getElementById('wordCount').value;
var wordbank = ['rock', 'paper', 'scissor', 'apple', 'beer', 'potato'];
var finalMessage = "";
for (i = 0; i < parseInt(wordCount, 10); i++) {
if (i > 0) finalMessage += " ";
finalMessage += wordbank[Math.floor(Math.random() * wordbank.length)];
}
var wordBin = document.getElementById('wordBin');
var wordBin2 = document.getElementById('wordBin2');
wordBin.innerHTML = finalMessage;
wordBin2.innerHTML = wordCount;
});
Updated Fiddle: http://jsfiddle.net/N988s/2/
Why not this:
<select id="wordCount" class="span2">
<option value="1">1 Word</option>
<option value="2">2 Words</option>
<option value="3">3 Words</option>
<option value="4">4 Words</option>
</select>
<input id="gen" type="submit" value="Generate">
<div id="wordBin"></div>
<div id="wordBin2"></div>
Js:
var wordbank = ['rock', 'paper', 'scissor', 'apple', 'beer', 'potato'];
$('#gen').click(function () {
var wordCount = document.getElementById('wordCount').value;
var wordBin = document.getElementById('wordBin');
words = '';
for (var i = 0; i < wordCount; i++) {
if (words != '') words += ' ';
words += getRandomWord();
wordBin.innerHTML = words;
}
});
function getRandomWord() {
return wordbank[Math.floor(Math.random()*wordbank.length)];
}
http://jsfiddle.net/N988s/3/