How to use class names? - javascript

I have an issue with something. I have 2 lists of options.
Every option in one list has a name of M, every option in the other has a name of R.
I need to select certain options, say 'A' and 'C' from both lists. I need to add an 'X' bonus to the 'X' options, and a 'Y' bonus to the 'Y' options ('B').
The bonus is in the form of a percentage
So the problem is, how do I select those options, and add the bonus? Can it be done? I have been told class names can solve it, but how do I do that?
<form action="">
<fieldset>
<head>
<script type="text/javascript">
function myFunction() {
/*Left flank bonus*/
var MLef1 = document.getElementById("MeleeL").value;
var RLef1 = document.getElementById("RangedL").value;
var ML = MLef1 - 0;
var RL = RLef1 - 0;
/*Melee total*/
var MT1 = ML;
var MT2 = MT1 / 100;
var MT = MT2 - 0;
/*Ranged total*/
var RT1 = RL;
var RT2 = RT1 / 100;
var RT = RT2 - 0;
/*Left flank normal*/
/*Left flank melee*/
var x = document.getElementById("Melee").selectedIndex;
var y = (document.getElementsByTagName("option")[x].value);
var xy = document.getElementById("LM1").value;
/*Left flank Ranged*/
var p = document.getElementById("Ranged").selectedIndex;
var o = (document.getElementsByName("LR")[p].value);
var i = document.getElementById("LM1").value;
/*Ranged*/
var c1 = o * i;
var c = c1 - 0;
var RTZ = RT * c;
var RTz = RTZ - 0;
/*Melee*/
var z2 = y * xy;
var z = z2 - 0;
var MTZ = MT * z;
var MTz = MTZ - 0;
/*Zero function*/
if (MT <= 0) {
(document.getElementById("result").innerHTML = z);
}
else if (MT > 0) {
(document.getElementById("result").innerHTML = MTz);
}
if (RT <= 0) {
(document.getElementById("result1").innerHTML = c);
}
else if (RT > 0) {
(document.getElementById("result1").innerHTML = RTz);
}
}
</script>
<legend align="center" id="Defense">Defense</legend>
<table>
<tr>
<th>Left Flank</th>
<th>
<th>
<th>Center Flank</th>
<th>Right Flank</th>
</tr>
<tr>
<td>
<label>X Bonus</label>
<br>
<label>Y bonus</label>
<br>
</td>
<td>
<input type="number" id="MeleeL">%
<br>
<input type="number" id="RangedL">%
<br>
</tr>
</table>
<select id="Melee">
<option value="11">A</option>
<option value="9">B</option>
<option value="6">C</option>
</select>
<input type="number" style="width:50px" id="LM1">
<select id="Ranged">
<option name="LR" value="17">A</option>
<option name="LR" value="4">B</option>
<option name="LR" value="36">C</option>
</select><br>
<button type="button" id="buton" onclick="myFunction()">Calculate</button><br>
<p id="result">The Melee, </p><p id="result1">The R, </p>
</fieldset>
</form>
This amount varies, and will be inputed through a input box. Again, I need the user to be able to add a variable bonus to some, but not all, of the options in a list.
Thanks for all the help!

I found out, using trial, error, and a couple hours reading coding manuals, how to do this. I am now using "data-name1". It helps a lot.
<script>
document.getElementById("selectElement").selectedIndex = -1; // so that no option //is selected when the page is loaded
// Good!!!
function getData(){
var e = document.getElementById("qwert"); // get the <select> element
// Understood
var data_name1 = e.options[e.selectedIndex].dataset.name1; // get the selected //<option> and its name1 data attribute
// var data_name2 = e.options[e.selectedIndex].dataset.name2; get the selected //<option> and its name2 data attribute
var value = e.options[e.selectedIndex].value; // get the value of the selected <option>
//Result
document.getElementById("data1").innerHTML = data_name1;
document.getElementById("value").innerHTML = value;
}
</script>
<select id="qwert" onclick="getData ()">
<option value="135" data-name1="M">Halberdier</option>
<option value="150" data-name1="R">Lancer</option>
<option value="51" data-name1="R">Longbowman</option>
<option value="27" data-name1="M">Militia</option>
</select>
<p>
<label>data-name1 = </label>
<span>"</span><span id="data1"></span><span>"</span>
</p>
<p>
<label>value = </label>
<span>"</span><span id="value"></span><span>"</span>
</p>
Thanks for all the help, sorry about being unclear.
All the best

Related

Show field based on selection (JS)

I'm trying to show fields based on what is selected in menu select option.
I tried some JS with the help of other posts found here on Stackoverflow, but failed.
I'm a fan, i dont know js well, i hope to find help with this question. Thanks to everyone for any answers, I leave the info below.
I would like to show the result of this:
var dayli_intake_mass = ((+ target) / 100 * (+ tdee) + (+ tdee));
only when mass1, mass2 or mass3 is selected.
Otherwise
I would like to show the result of this:
var dayli_intake_def = ((+ tdee) - (+ target) / 100 * (+ tdee));
only when def1, def2 or def3 is selected.
So, the mass1, mass2 and mass3 selection should show dayli_intake_mass
While the selection def1, def2 and def3 should show dayli_intake_def
Point 1 is an addition, point 2 is a subtraction. I don't want both to be visible, but only one of the two fields based on the selection.
I apologize for the bad English :(
<div class="fieldcontainer">
<input oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);" type="number" class="mts-field" maxlength="4" id="tdee" name"tdee" placeholder="Inserisci il tuo TDEE" form="fbday" required autocomplete="off"/>
<label>Spesa calorica</label>
</div>
<div class="container_level">
<select class="target" id="target_select" form="fbday" name="target">
<option value="0">Stile di vita / Attività fisica</option>
<option id="mass1" name="radsa" value="5">mass1</option>
<option id="mass2" name="radsa" value="10">mass2</option>
<option id="mass3" name="radsa" value="15">mass3</option>
<option id="def1" name="radsa" value="10">def1</option>
<option id="def2" name="radsa" value="15">def2</option>
<option id="def3" name="radsa" value="20">def3</option>
</select>
</div>
<!---Fabbisogno Giornaliero--->
<div id="fbbday0" class="results" hidden>
<input type="text" form="fbday" class="result-field" id="dayli_intake_mass" name="dayli_intake"
placeholder="Fabbisogno giornaliero / 0.000 Kcal" min="1" readonly/>
<label class="mts-label"></label>
</div>
<div id="fbbday1" class="results" hidden>
<input type="text" form="fbday" class="result-field" id="dayli_intake_def" name="dayli_intake"
placeholder="Fabbisogno giornaliero / 0.000 Kcal" min="1" readonly/>
<label class="mts-label"></label>
</div>
<form action="" id="fbday">
</form>
<button name="calculate" onclick="calculate()">Calculate</button>
<button id="reset" onclick="resetFields()">Reset</button>
calculate = function()
{
var tdee = document.getElementById('tdee').value;
var target = document.querySelector('#target_select option:checked').value;
var dayli_intake_mass = ((+target)/100*(+tdee)+(+tdee));
var kcal = "Devi assumere "+dayli_intake_mass.toLocaleString('it-IT',{maximumFractionDigits: 0}) + " Kcal"; document.getElementById('dayli_intake_mass').value = kcal;
var dayli_intake_def = ((+tdee)-(+target)/100*(+tdee));
var kcal = "Devi assumere "+dayli_intake_def.toLocaleString('it-IT',{maximumFractionDigits: 0}) + " Kcal"; document.getElementById('dayli_intake_def').value = kcal;
//This is Target Radio Selection//
var mass1 = document.getElementById('mass1').value;
var mass2 = document.getElementById('mass2').value;
var mass3 = document.getElementById('mass3').value;
var def1 = document.getElementById('def1').value;
var def2 = document.getElementById('def2').value;
var def3 = document.getElementById('def3').value;
//This is HideShow Result//
var conditional = document.querySelector('#target_select option:checked').value;
document.getElementById('dayli_intake_mass').hidden = conditional !== '5';
document.getElementById('dayli_intake_mass').hidden = conditional !== '10';
document.getElementById('dayli_intake_mass').hidden = conditional !== '15';
document.getElementById('dayli_intake_def').hidden = conditional !== '10';
document.getElementById('dayli_intake_def').hidden = conditional !== '15';
document.getElementById('dayli_intake_def').hidden = conditional !== '20';
}
https://jsfiddle.net/snake93/w1nLbhxv/81/
Edited
you can use change event to handle that
when you select one of the list it's will call change event then check or execute your code
because of there's some values like each other for example mass2 value = 10 and also def1 value = 10 .
because of that you can't only compare the values but also you need to compare the element id so i added the id's in the comparison operation
Here's the code
var target_select = document.getElementById("target_select");
target_select.addEventListener("change", function () {
var tdee = document.getElementById('tdee').value;
var target = document.querySelector('#target_select option:checked');
var fbbday1 = document.getElementById('fbbday1'),
fbbday0 = document.getElementById('fbbday0')
var dayli_intake_mass = ((+target.value)/100*(+tdee)+(+tdee));
var dayli_intake_def = ((+tdee)-(+target.value)/100*(+tdee));
//This is Target Radio Selection//
var mass1 = document.getElementById('mass1').value;
var mass2 = document.getElementById('mass2').value;
var mass3 = document.getElementById('mass3').value;
var def1 = document.getElementById('def1').value;
var def2 = document.getElementById('def2').value;
var def3 = document.getElementById('def3').value;
var massArr = [mass1, mass2, mass3],
deffArr = [def1, def2, def3]
if(massArr.indexOf(this.value) != -1 && target.id === 'mass1' || target.id === 'mass2' || target.id === 'mass3') {
fbbday0.removeAttribute('hidden')
document.getElementById('dayli_intake_mass').value = dayli_intake_mass;
} else {
fbbday0.setAttribute('hidden', true)
}
if(deffArr.indexOf(this.value) != -1 && target.id === 'def1' || target.id === 'def2' || target.id === 'def3') {
fbbday1.removeAttribute('hidden')
document.getElementById('dayli_intake_def').value = dayli_intake_def;
} else {
fbbday1.setAttribute('hidden', true)
}
});
First, I edited the values of the select options to be as below:
<select class="target" id="target_select" form="fbday" name="target" (onChange)="showHideIntake($event)">
<option value="0">Stile di vita / Attività fisica</option>
<option id="mass1" name="radsa" value="5">mass1</option>
<option id="mass2" name="radsa" value="10">mass2</option>
<option id="mass3" name="radsa" value="15">mass3</option>
<option id="def1" name="radsa" value="-10">def1</option>
<option id="def2" name="radsa" value="-15">def2</option>
<option id="def3" name="radsa" value="-20">def3</option>
</select>
Second, I added an event called (onChange) to the select element as shown in the first line in the previous point.
Third, I added an eventListener to the select element to handle the (onChange) event, as below:
const target_select = document.querySelector('#target_select');
const dayli_intake_mass = document.querySelector('#dayli_intake_mass');
const dayli_intake_def = document.querySelector('#dayli_intake_def');
target_select.addEventListener('change', (event) => {
console.log(+event.target.value); // just for checking selected option
// the + (plus sign) is to convert from string to number
dayli_intake_mass.hidden = dayli_intake_def.hidden = true;
event.target.value > 0 ? dayli_intake_mass.hidden = false :
dayli_intake_def.hidden = false;
});
With this, dayli_intake_mass and dayli_intake_def are shown or hidden upon the select option. Plus, you can use the value of the select option directly upon select one option of them.

How to get total sum result from 2 array and split into multiple input?

Well im still new into javascript and need some help about getting total sum of 2 select which each option having different array. Plus, the total sum will be shown at multiple input. (I dont know what is this method called).
I tried and google alot still does not works and I know some code is missing.
That Output1 and Output2 just to check that they are calling the array.
<select id="firstselect" onchange="total()">
<option value="0"> Choose </option>
<option value="1"> Option A </option>
<option value="2"> Option B </option>
</select>
<select id="secondselect" onchange="total()">
<option value="0"> Choose </option>
<option value="1"> Option D </option>
<option value="2"> Option E </option>
</select>
<p id="output1"></p>
<p id="output2"></p>
<input id="inputA" disabled> INPUT A </input>
<input id="inputB" disabled> INPUT B </input>
<input id="inputC" disabled> INPUT C </input>
<input id="inputD" disabled> INPUT D </input>
<input id="inputE" disabled> INPUT E </input>
<input id="inputF" disabled> INPUT F </input>
var inputA = document.getElementById("inputA");
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var inputD = document.getElementById("inputD");
var inputE = document.getElementById("inputE");
var inputF = document.getElementById("inputF");
//FIRSTSELECT 0=inputA, 1=inputB 2=inputC 3=inputD 4=inputE 5=inputF
var value1 = [0,1,2,3,4,5];
var value2 = [1,2,3,4,5,6];
//SECONDSELECT 0=inputA, 1=inputB 2=inputC 3=inputD 4=inputE 5=inputF
var value3 = [2,3,4,5,6,7];
var value4 = [3,4,5,6,7,8];
function fs1() {
var fs = document.getElementById('firstselect').value;
if(fs == 0) {fs = 0;}
if(fs == 1) {fs = value1;}
if(fs == 2) {fs = value2;}
document.getElementById("output1").innerHTML = fs ;
return fs;
inputA.value = fs[0];
inputB.value = fs[1];
inputC.value = fs[2];
inputD.value = fs[3];
inputE.value = fs[4];
inputF.value = fs[5];
}
function ss1(){
var ss = document.getElementById('secondselect').value;
if(ss == 0) {ss = 0;}
if(ss == 1) {ss = value3;}
if(ss == 2) {ss = value4;}
document.getElementById("output2").innerHTML = ss;
return ss;
inputA.value = ss[0];
inputB.value = ss[1];
inputC.value = ss[2];
inputD.value = ss[3];
inputE.value = ss[4];
inputF.value = ss[5];
}
function total(){
var total = parseInt(fs1()) + parseInt(ss1());
}
The result should be like this :
inputA.value = fs[0] + ss[0],
inputB.value = fs[1] + ss[1] and it goes until [5]
If I understood your question correctly, I hope it fits
It works!
//FIRSTSELECT 0=inputA, 1=inputB 2=inputC 3=inputD 4=inputE 5=inputF
var value1 = [0,1,2,3,4,5];
var value2 = [1,2,3,4,5,6];
//SECONDSELECT 0=inputA, 1=inputB 2=inputC 3=inputD 4=inputE 5=inputF
var value3 = [2,3,4,5,6,7];
var value4 = [3,4,5,6,7,8];
function ss(){
var ss = document.getElementById('secondselect').value;
if(ss == 0) {ss = 0;}
if(ss == 1) {ss = value3;}
if(ss == 2) {ss = value4;}
document.getElementById("output2").innerHTML = ss;
return ss;
}
function fs1() {
var fs = document.getElementById('firstselect').value;
if(fs == 0) {fs = 0;}
if(fs == 1) {fs = value1;}
if(fs == 2) {fs = value2;}
document.getElementById("output1").innerHTML = fs ;
return fs;
}
function total(){
debugger;
var fs=fs1();
var ss1=ss();
var arrResult=[];
if(fs && fs.length>0 && ss1 && ss1.length>0 ){
for (var i = 0; i < 6; i++) {
arrResult.push(+fs[i] + +ss1[i])
}
}
var inputA = document.getElementById("inputA");
var inputB = document.getElementById("inputB");
var inputC = document.getElementById("inputC");
var inputD = document.getElementById("inputD");
var inputE = document.getElementById("inputE");
var inputF = document.getElementById("inputF");
inputA.value = arrResult[0]?arrResult[0]:'';
inputB.value = arrResult[1]?arrResult[1]:'';
inputC.value = arrResult[2]?arrResult[2]:'';
inputD.value = arrResult[3]?arrResult[3]:'';
inputE.value = arrResult[4]?arrResult[4]:'';
inputF.value = arrResult[5]?arrResult[5]:'';
}
<select id="firstselect" onchange="total()">
<option value="0"> Choose </option>
<option value="1"> Option A </option>
<option value="2"> Option B </option>
</select>
<select id="secondselect" onchange="total()">
<option value="0"> Choose </option>
<option value="1"> Option D </option>
<option value="2"> Option E </option>
</select>
<p id="output1"></p>
<p id="output2"></p>
<input id="inputA" disabled> INPUT A </input>
<input id="inputB" disabled> INPUT B </input>
<input id="inputC" disabled> INPUT C </input>
<input id="inputD" disabled> INPUT D </input>
<input id="inputE" disabled> INPUT E </input>
<input id="inputF" disabled> INPUT F </input>

How can I create a chart/plot in JavaScript with just a SINGLE calculated number?

I was wondering how I can incorporate a plot or chart into JavaScript to plot ONE number. It's kind of a just an entertaining piece I'm doing. I eventually want it to be a "stress test" with the number that is calculated from my equation. Any idea on how to do this?
Here is my jsfiddle:
https://jsfiddle.net/avanhout13/em5vq8Ld/
HTML:
Calculate Stress
<FORM name="stress">
<A NAME="stress"></A>
Calculate Stress<br>
Enter Value<br>
Force: <INPUT TYPE="text" SIZE="7" maxlength="15" NAME="force">
<SELECT NAME="forceunits">
<OPTION VALUE="1" selected>Newtons</OPTION>
<OPTION VALUE="0.00001">Dyne</OPTION>
<OPTION VALUE="0.00980665 ">Gram Force</OPTION>
<OPTION VALUE="1">Kgs-Meter/sec^2</OPTION>
<OPTION VALUE="9.80665 ">Kilograms Force</OPTION>
<OPTION VALUE="4448.22161526">Kip</OPTION>
<OPTION VALUE=" 4.44822162 ">Pound Force</OPTION>
<OPTION VALUE=" 0.138254954376 ">Poundal</OPTION>
</SELECT>
<br>
Area: <INPUT TYPE="text" SIZE="7" maxlength="15" NAME="area">
<SELECT NAME="areaunits">
<OPTION VALUE="1" selected>Metre^2</OPTION>
<OPTION VALUE="100">Are</OPTION>
<OPTION VALUE="1e-28">Barn</OPTION>
<OPTION VALUE="0.0001">Centimetre^2</OPTION>
<OPTION VALUE="0.09290304">Foot^2</OPTION>
<OPTION VALUE="10000">Hectare</OPTION>
<OPTION VALUE="0.00064516">Inch^2</OPTION>
<OPTION VALUE="2589988.11034">Mile^2</OPTION>
<OPTION VALUE="1000000">Kilometre^2</OPTION>
<OPTION VALUE=" 0.83612736">Yard^2</OPTION>
</SELECT>
<br>
<INPUT TYPE="button" VALUE=" Calculate "
onClick="calcstress(this.form)" >
<input type="reset" value="Clear" style="margin-left:.5cm">
<br><br>
Result:<br><br>
Stress:
<INPUT TYPE="text" SIZE="12" maxlength="15" VALUE="" NAME="result"> Newton / Meter<sup>2</sup>
JAVASCRIPT:
function calcstress(){
var form = document.stress;
var i = form.forceunits.selectedIndex;
var forceunitsvalue = form.forceunits.options[i].value;
var j = form.areaunits.selectedIndex;
var areaunitsvalue = form.areaunits.options[j].value;
var f = form.force.value;
var a = form.area.value;
var result = (f * forceunitsvalue) / (a * areaunitsvalue);
form.result.value = roundoff(result,7);
return true;
}
function roundoff(x,y){
x = parseFloat(x);
y = parseFloat(y);
x = Math.round(x * Math.pow(10,y))/Math.pow(10,y);
return x;
}
function calcforce(){
var form = document.force;
var i = form.stressunits.selectedIndex;
var stressunitsvalue = form.stressunits.options[i].value;
var j = form.areaunits.selectedIndex;
var areaunitsvalue = form.areaunits.options[j].value;
var s = form.stress.value;
var a = form.area.value;
var result = (s * stressunitsvalue) * (a * areaunitsvalue);
form.result.value =result;
return true;
}
function roundoff(x,y){
x = parseFloat(x);
y = parseFloat(y);
x = Math.round(x * Math.pow(10,y))/Math.pow(10,y);
return x;
}
function calcarea(){
var form = document.area;
var i = form.forceunits.selectedIndex;
var forceunitsvalue = form.forceunits.options[i].value;
var j = form.stressunits.selectedIndex;
var stressunitsvalue = form.stressunits.options[j].value;
var f = form.force.value;
var s = form.stress.value;
var result = (f * forceunitsvalue) / (s * stressunitsvalue);
form.result.value = result;
return true;
}
function roundoff(x,y){
x = parseFloat(x);
y = parseFloat(y);
x = Math.round(x * Math.pow(10,y))/Math.pow(10,y);
return x;
}
You can easily make charts using google charts:
Just add following CDN in your html file:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
Then make your data appropriate to charts data.
like:
var data = google.visualization.arrayToDataTable([
['City', '2010 Population', '2000 Population'],
['New York City, NY', 8175000, 8008000],
['Los Angeles, CA', 3792000, 3694000],
['Chicago, IL', 2695000, 2896000],
['Houston, TX', 2099000, 1953000],
['Philadelphia, PA', 1526000, 1517000]
Here is the Jsfiddle

How do I get the sum of radio buttons groups using parameters instead of values

I have multiple sets of radio buttons where the selected values of each set need to be added and displayed to the user. So far I have been changing the values in the function in a switch statement to handle the addition.
<form name="config" id="config">
<div class="row-fluid">
<h3>Memory</h3>
<input type="radio" name="section1" value="4gb" onclick="changePrice(0)" checked>4gb<br>
<input type="radio" name="section1" value="8gb" onclick="changePrice(100)">8gb (+$100)<br>
<input type="radio" name="section1" value="16gb" onclick="changePrice(200)">16gb (+$200)
</div>
<div class="row-fluid">
<h3>Primary Hard Drive</h3>
<input type="radio" name="section2" value="dell" onclick="changePrice(0)" checked>Dell<br>
<input type="radio" name="section2" value="asus" onclick="changePrice(100)">Asus(+$100)
</div>
</form>
<div id="price"></div>
The script I am using right now is
var displayPrice = document.getElementById("price");
var baseNum = 200;
displayPrice.innerHTML = baseNum;
function(changePrice){
var val1, val2;
switch(document.config.section1.value){
case "4gb":
val1 = 0;
break;
case "8gb":
val1 = 100;
break;
case "16gb":
val1 = 200;
break;
default:
val1 = 0;
}
switch(document.config.section2.value){
case "dell":
val1 = 0;
break;
case "asus":
val1 = 100;
break;
default:
val1 = 0;
}
var sum = val1 + val2 + baseNum;
displayPrice.innerHTML = sum;
}
Is there a way I can do these calculations using the parameters passed through the changePrice function (so I don't have to change the values in the switch statements)?
Here's how to do this without jQuery.
You'll need to tell the changePrice function which section it should change the price for so you'll need to change the calls to look like this changePrice(1, 100) where 1 is the section and 100 is the price change. Then you can collect all the section prices individually and sum them like so:
var displayPrice = document.getElementById("price");
var baseNum = 200;
displayPrice.innerHTML = baseNum;
var sections = {};
function changePrice(section,val){
// add or update the section value
sections[section] = val;
// start with the base price
var sum = baseNum;
// loop over all the sections and add them to the base price
for(var key in sections) {
sum = sections[key] + sum;
}
displayPrice.innerHTML = sum;
}
Here's a jsfiddle
If you change your function definition to the following, it will take in your parameter.
function changePrice(val1)
If you could change your the value attribute on each of your input fields to contain your increment value, it would make the process of calculating your sum much easier. (This may not be appropriate to the problem you are trying to solve.
Basic solution with jQuery
var sum = $("input[name=section1]").val() + $("input[name=section2]").val();
If your list is very long, you could iterate over your radio button sets with jQuery
var sum = 0;
$("input[type=radio]").each(function(){sum += $(this).val();});
<html>
<head>
<script type="text/javascript">
function DisplayPrice(price){
var val1 = 0;
for( i = 0; i < document.form1.R1.length; i++ ){
if( document.form1.R1[i].checked == true ){
val1 = document.form1.R1[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.R2.length; i++ ){
if(document.form2.R2[i].checked == true ){
val2 = document.form2.R2[i].value;
}
}
var sum=parseInt(val1) + parseInt(val2);
document.getElementById('totalSum').innerHTML=sum;
}
</script>
</head>
<body>
Choose a number:<br>
<form name="form1" id="form1">
<br>
R1 <input id="rdo_1" type="radio" value="5" name="R1" onClick="DisplayPrice(this.value);" checked>5
<br>
R1 <input id="rdo_2" type="radio" value="10" name="R1" onClick="DisplayPrice(this.value);">10
<br>
</form>
Choose another number:<br>
<form name="form2" id="form2">
<br>
R2 <input id="rdo_1" type="radio" value="15" name="R2" onClick="DisplayPrice(this.value);" checked>15
<br>
R2 <input id="rdo_2" type="radio" value="20" name="R2" onClick="DisplayPrice(this.value);">20
<br>
</form>
Your total is Rs = <span name="totalSum" id="totalSum" > 20</span>
</body>
</html>

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