How to find average of innerHTMLs? - javascript

I have input fields and selects. For different select options there are different equations. After calculating equations, I used .innerHTML to show results. I got first part of the code worked, but I am stuck at the last part. When I try to calculate average of outputs, It shows Nan. Can anyone help with this problem? Thanks in advance.
var container = document.getElementById('container');
var span1 = document.getElementById('span1');
var span2 = document.getElementById('span2');
var output = document.getElementById('output');
function average() {
var a = parseFloat(document.getElementById('a').value);
var b = parseFloat(document.getElementById('b').value);
var c = parseFloat(document.getElementById('c').value);
var d = parseFloat(document.getElementById('d').value);
if (document.getElementById('select1').value == '1') {
span1.innerHTML = ((a+b)/(a*b)).toFixed(2);
} else if (document.getElementById('select1').value == '2') {
span1.innerHTML = ((a*b)/(a+b)).toFixed(2)
} else {
span1.innerHTML = '';
}
if (isNaN(span1.innerHTML)) {
span1.innerHTML = '';
}
if (document.getElementById('select1').value == 'none1') {
span1.innerHTML = 'None'
}
if (document.getElementById('select2').value == '3') {
span2.innerHTML = ((c+d)*100/(c*d)).toFixed(2);
} else if (document.getElementById('select2').value == '4') {
span2.innerHTML = ((c*d)*100/(c+d)).toFixed(2)
} else {
span2.innerHTML = '';
}
if (isNaN(span2.innerHTML)) {
span2.innerHTML = '';
}
if (document.getElementById('select2').value == 'none2') {
span2.innerHTML = 'None'
}
var percent = document.getElementsByClassName('percent');
for (var i = 0; percent.length > i; i++) {
if (percent.length > 0) {
output.innerHTML = percent[i]/(percent.length);
}
}
}
container.addEventListener('change', average);
container.addEventListener('input', average);
<div id="container">
<input id="a" type="number">
<input id="b" type="number">
<select name="abc" id="select1">
<option value="Choose">Choose...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="none1">None</option>
</select>
<br>
<input id="c" type="number">
<input id="d" type="number">
<select name="abcd" id="select2">
<option value="Choose">Choose...</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="none2">None</option>
</select>
<span id="span1" class="percent"></span>
<span id="span2" class="percent"></span><br>
<span id="output"></span>
</div>

.innerHTML gets or sets the content of an element by invoking the HTML parser on the string passed as the value or extracted from the element. When the content is, or is to become just text (no HTML to be parsed), you should use .textContent as this will not invoke the HTML parser on the content, which saves processing power. In your case, you should be using .textContent.
Now, either way, data sent to or gotten from either .innerHTML or .textContent is a string, so if you want to do math with the value, you need to first convert it to a number. This can be done in several ways:
parseInt(stringToBeConverted, radix)
parseFloat(stringToBeConverted)
Number(stringToBeConverted)
+stringToBeConverted
Now, you have two issues, first when some of the text fields are still empty, their value is an empty string and parseFloat() on an empty string returns NaN. This can be solved by giving each field a default value of 0 in the HTML (i.e. <input id="a" type="number" value="0">).
Second, even with a, b, c, and d all having numeric values, your math:
((a + b) / (a * b)).toFixed(2);
Will result in NaN when a * b results in 0 because that will result in a division by zero situation.
You need to change your algorithm to test for this situation before doing the math.

I have no idea what you're trying to do, but I think this might be the correct solution it's a working way of getting the value of the percent[i] HTML element:
Change
output.innerHTML = percent[i]/(percent.length);
to
output.innerHTML = percent.item(i).innerHTML/(percent.length);
or
output.innerHTML = percent[i].innerHTML/(percent.length);

Related

passing option value in html as javascript parameter

I made a simple html and javascript file to help me roll dice in DND. Currently this seems to be working fine
index.html
<form>
<input type="number" id="diceType"> dice type (d20, d12 ect ...)<br>
<input type="number" id="diceNumber"> number of dice<br>
<input type="number" id="mod"> mod<br>
</form>
<button type="button" onclick="roll(document.getElementById('diceType').value, document.getElementById('diceNumber').value, document.getElementById('mod').value)">
Roll
</button>
index.js
const roll = function(diceType, diceNumber, mod){
let total = 0;
let div1 = document.getElementById("rolling");
div1.innerHTML = '';
for(let i = 0; i < diceNumber; i++){
let roll = Math.floor(Math.random() * (diceType - 1 + 1) ) + 1;
total += roll;
div1.innerHTML += 'you rolled ' + roll + "<br>";
}
let result = parseInt(total) + parseInt(mod);
document.getElementById("youRolled").innerHTML =
'You rolled ' + diceNumber + 'D' + diceType + ' modifier was ' + mod + ' total: ' + result
};
However, I find this a little clunky as I want to have a selection drop down list, have the user select the option, then pass that as a parameter to the roll function.
I have tried using
<select>
<option value="100">D100</option>
<option value="20">D20</option>
<option value="12">D12</option>
<option value="10">D10</option>
<option value="8">D8</option>
<option value="6">D6</option>
<option value="4">D4</option>
</select>
I have tried a few things but I was wondering how would I access say
<option value="12">D12</option>
that value then pass it into
onclick="roll()"
as one of the parameters. That why I figure it would prevent me or others from selecting a million different dice combinations to enter. Also, I do know there is other generators out there, but was looking to try and make my own for fun.
Inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead, eg: https://developer.mozilla.org/en/DOM/element.addEventListener
Like this:
const fields = ['diceType', 'diceNumber', 'mod'].map(id => document.getElementById(id));
document.querySelector('button')
.addEventListener('click', () => roll(...fields.map(field => field.value)));
And for the roll function:
const roll = function(diceType, diceNumber, mod){
const selectedValue = document.querySelector('select').value;
let total = 0;
// ...
values are strings, so if needed, to turn selectedValue into a number, call Number on it while defining the variable:
const selectedValue = Number(document.querySelector('select').value);
In your code you have to add id to the <select> tag
If you have a select element that looks like this:
<select id="diceValue">
<option value="100">D100</option>
<option value="20">D20</option>
<option value="12">D12</option>
<option value="10">D10</option>
<option value="8">D8</option>
<option value="6">D6</option>
<option value="4">D4</option>
</select>
Running this code:
var e = document.getElementById("diceValue");
var value = e.options[e.selectedIndex].value;
Would make value to be option value. If what you actually want is D100, then do this:
var e = document.getElementById("diceValue");
var value = e.options[e.selectedIndex].text;
Which would make value be D100.
To pass the value inside the function just use :
onClick = roll(document.getElementById('diceValue').value ,..other arguments)

Copy text from text box onkeyinput to other textbox based on dropdown?

Good day.
I need to copy what's being typed into a textbox to multiple other text boxes.
The catch is that there is a dropdown which must determine this.
The process: User will enter a "Commodity" into the "Commodity" text box.
After this, they will then select from a dropdown the number of "Delivery Places". If they choose "1"; textbox "Commodity1" will have the same contents as the main "Commodity" textbox.
If they choose "2" as "DeliveryPlaces", both "Commodity1" & "Commodity2" will have the contents typed into "Commodity". This process should follow until "5" for "DeliveryPlaces".
The reason I want it done like this is that most of our clients will only order one type of commodity, even though it will be transported to multiple locations;
function copy(){
if (document.getElementById("DeliveryPlaces").value = "1")
{
document.getElementById("Commodity1").value=document.getElementById("Commodity").value;
}
else if (document.getElementById("DeliveryPlaces").value = "2")
{
document.getElementById("Commodity1").value=document.getElementById("Commodity").value;
document.getElementById("Commodity2").value=document.getElementById("Commodity").value;
}
else if (document.getElementById("DeliveryPlaces").value = "3")
{
document.getElementById("Commodity1").value=document.getElementById("Commodity").value;
document.getElementById("Commodity2").value=document.getElementById("Commodity").value;
document.getElementById("Commodity3").value=document.getElementById("Commodity").value;
}
else if (document.getElementById("DeliveryPlaces").value = "4")
{
document.getElementById("Commodity1").value=document.getElementById("Commodity").value;
document.getElementById("Commodity2").value=document.getElementById("Commodity").value;
document.getElementById("Commodity3").value=document.getElementById("Commodity").value;
document.getElementById("Commodity4").value=document.getElementById("Commodity").value;
}
else if (document.getElementById("DeliveryPlaces").value = "5")
{
document.getElementById("Commodity1").value=document.getElementById("Commodity").value;
document.getElementById("Commodity2").value=document.getElementById("Commodity").value;
document.getElementById("Commodity3").value=document.getElementById("Commodity").value;
document.getElementById("Commodity4").value=document.getElementById("Commodity").value;
document.getElementById("Commodity5").value=document.getElementById("Commodity").value;
}
else
{
document.getElementById("Commodity1").value="";
document.getElementById("Commodity2").value="";
document.getElementById("Commodity3").value="";
document.getElementById("Commodity4").value="";
document.getElementById("Commodity5").value="";
}
}
<p>
Commodity
</p><input type="textbox" id="Commodity" onkeyinput="copy();">
<p>
Commodity1
</p><input type="textbox" id="Commodity1">
<p>
Commodity2
</p><input type="textbox" id="Commodity2">
<p>
Commodity3
</p><input type="textbox" id="Commodity3">
<p>
Commodity4
</p><input type="textbox" id="Commodity4">
<p>
Commodity5
</p><input type="textbox" id="Commodity5">
<p>
Delivery Places
</p>
<select style="width:50px;" id="DeliveryPlaces">
<option value="-">-</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
so by filling it in automatically we save the user some time.
I managed to get it working without the if conditions, that was simple enough. Now, however, it's only filling in "Commodity1" even though I choose a "DeliveryPlace" which IS NOT "1".
Any help would be appreciated.
Switch:
if (document.getElementById("DeliveryPlaces").value = "1")
to
if (document.getElementById("DeliveryPlaces").value == "1")
The code is actually switching DeliveryPlaces to 1 in your statement
Try using:
var e = document.getElementById("DeliveryPlaces")
var selection = e.options[e.selectedIndex].value;
Then do your condition based on the value in selection.
you are currently selecting the value of the Select element not the option you have actually selected.
Edit: it may be text rather than value you need on your selection, but give it a go!
I would do it like this:
function copy() {
var e = document.getElementById("DeliveryPlaces")
var selection = parseInt(e.options[e.selectedIndex].value);
var input = document.getElementById("Commodity").value;
var field;
for (var i = 1; i < 6; i++) {
field = "Commodity" + i;
if (i <= selection) {
document.getElementById(field).value = input;
} else {
document.getElementById(field).value = "";
}
}
}
This way, you can clear the other commodities, when you change to a lower delivery place + you can easily add more by editing the for loop.
Your function should receive the number of the dropdown. That is, if you selected 2 copy (2) so you can use a for and go through the ones you want to fill
for (i = item.length; i = 0; i--) {
document.getElementById("Commodity"+i).value=document.getElementById("Commodity").value;
}
The for will go from low to high until it reaches 0. that means that it will count if it is 5. 5,4,3,2,1 and will fill all the fields that you want. This avoids the amount of spaghetti code you have in your structure.
I understand that you are using pure javascript. But you could use jquery and it would make the job easier.

How to compare <option> “data-names” in an “if” statement?

I have a slight issue. I have options with a “value” and a “data-name”.
<option value=”A” data-name1=”X”>
<option value=”B” data-name1=”Y”>
I want the computer return a specific value if the selected option is a certain “data-name”
Say there are 2 “data-names”, X and Y.
How can I compare the data-name of the selected option to the 2 data-names, X and Y, to find out which one it is?
I’m thinking something along the lines of this:
var data_name1 = e.options[e.selectedIndex].dataset.name1;
if (data_name1 == “X”) {
…
}
else if (data_name == “Y”) {
…
}
else {
…
}
Is this possible?
Thanks!
Full code---
<script>
document.getElementById("selectElement").selectedIndex = -1; // so that no option //is selected when the page is loaded
function getData(){
var e = document.getElementById("qwert"); // get the <select> element
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">A</option>
<option value="150" data-name1="R">B</option>
<option value="51" data-name1="R">C</option>
<option value="27" data-name1="M">D</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>
You need to use the == operator to compare objects.
= is an assignment expression.
if (data_name1 == “X”) {
// Operations if data_name is equal to X
}
else if (data_name == “Y”) {
// Operations is data_name is equal to Y
}
else {
}

Javascript If statement with boolean value

I have two dropdown select boxes and I want a textbox to update with a value based on the selected texts from the two boxes.
If the first box selected is 'dollars' and the second is 'naira', I want the rate to be 100 and this value inputted in the textbox with the id of rate.
Unfortunately when my function executes I keep getting a value of undefined. Something is obviously wrong with my if statement but I can't figure it out.I need to do this with pure javascript, not jquery.
Here is my code:
<p>Select currency to send</p>
<select id="fromCurrency">
<option value = "Dollars">Dollars</option>
<option value = "Pounds">Pounds</option>
<option value = "Naira">Naira</option>
</select>
<p>Select currency to receive</p>
<select id="toCurrency">
<option value = "Naira">Naira</option>
<option value = "Dollars">Dollars</option>
<option value = "Pounds">Pounds</option>
</select><br />
<label>Enter amount to send</label>
<input type="text" id="amount" name="amount"><br />
<button onclick ="getRate()">Get Rate</button><br />
<label>Rate:</label>
<input type="text" id="rate" name="rate"><br />
<label>Total:</label>
<input type="text" id="total" name="total"><br />
<script>
function getRate() {
var e = document.getElementById("fromCurrency");
var eSend = e.options[e.selectedIndex].value;
var i = document.getElementById('toCurrency');
var eReceive = i.options[i.selectedIndex].value;
var rate = document.getElementById('rate');
var dollars = {
'pounds':20,
'naira':15
};
if (eSend =='dollars' && eReceive =='naira') {
var rValue= (dollars['pounds']);
};
rate.value = rValue;
};
</script>
Please advice.
Thanks
EDIT:
I tried to use a switch statement as I have about 6 different conditions, and this is what I tried but it didn't work.
var rValue = 0;
switch (rValue) {
case (eSend =='Dollars' && eReceive =='Naira'):
rValue= (dollars['naira']);
break;
case (eSend =='Dollars' && eReceive =='Pounds'):
rValue= (dollars['pounds']);
break;
}
rate.value = rValue;
JavaScript is case-sensitive, your if statement:
if (eSend =='dollars' && eReceive =='naira') {
is looking for dollars, not Dollars, capitalize to match your select values:
if (eSend =='Dollars' && eReceive =='Naira') {

drop down list with more then one dilimiter. can get JS to work

Ok so i am trying to get a textarea where a user can type in text. select a delimiter from a dropdown list. Hit count and it will count how many times it splits.
I cant seem to get my code to split at all. here is my code.
JavaScript
window.onload = function() {
document.getElementById("change").onclick = function() {
var paragraph = document.getElementById('box').value;
var x = document.getElementById("changeCase");
var getInfo = document.getElementById('ParaWrite');
var LowerCase = " ";
var splitAT = " ";
alert("above the for loop");
if (x.checked === true)
{
LowerCase = paragraph.toLowerCase();
}
else
{
LowerCase = paragraph;
}
for (var i = 0; i <document.form1.split.options.length; i++)
{
if (document.form1.split.options[i].selected === true)
{
splitAT = paragraph.split(options[i]);
}
}
document.write(splitAT);
doc write is just so i can see if it even makes it that far in the code and it does not.
here is my HTML
<form name="form1" id="form1">
<textarea type="text" id="box" value=""/></textarea>
<input type='checkbox' name='write' id='changeCase' value='Check'/><br>
<input type='button' value="Count" id="change"/>
<select name="split" id="split">
<option value="like">like</option>
<option value="monkey">monkey</option>
<option value="I">I</option>
<option value=".">.</option>
<option value=",">,</option>
<option value="?">?</option>
<option value=" ">[Space]</option>
</select>
</form>
<div id="ParaWrite">
</div>
options is not defined.
splitAT = paragraph.split(document.form1.split.options[i]);
http://jsfiddle.net/ExplosionPIlls/KeZEd/

Categories