JavaScript - How This Can Be Written In Few Lines? [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm trying to learn JS. For several hours I've been struggling with connecting things to array, then adding functions, I wanted it to go with .forEach blabla.. Kinda gave up and made it the longer and not really complicated, easiest way which I really dislike. If you could give me any tips how to write this shorter I would be very grateful.
function calc() {
var hp = document.getElementById("hpMob").value;
var hpz = "potwor posiada: " + document.getElementById("hpMob").value;
var a = "Flame dmg: " + (hp * 0.05) * document.getElementById("resFire").value /100;
var b = "Freeze dmg: " + (hp * 0.05) *document.getElementById("resIce").value /100;
var c = "Divine dmg: " + (hp * 0.05) * document.getElementById("resHoly").value /100;
var d = "Zap dmg: " + (hp * 0.05) * document.getElementById("resEnergy").value /100;
var e = "Wound dmg: " + (hp * 0.05) * document.getElementById("resPhysic").value /100;
var f = "Poison dmg: " + (hp * 0.05) * document.getElementById("resEarth").value /100;
var g = "Curse dmg: " + (hp * 0.05) * document.getElementById("resDeath").value /100;
/* var allId =
document.getElementById("resFire").value;
+ document.getElementById("resIce").value;
+ document.getElementById("resHoly").value;
+ document.getElementById("resEnergy").value;
+ document.getElementById("resPhysic").value;
+ document.getElementById("resEarth").value;
+ document.getElementById("resDeath").value;
*/
// var lista = [a, b, c, d, e, f, g];
var tekstPisany = hpz + "<br>" + a + "<br>" + b + "<br>" + c + "<br>" + d + "<br>" + e + "<br>"+ f + "<br>" + g + "<br>";
document.getElementById("result").innerHTML = tekstPisany;
};
<form> <center>
HP Moba: <input type="text" class="hp" id="hpMob"><br /><br />
Fire: <input type="text" class="x" id="resFire"> <br />
Ice: <input type="text" class="x" id="resIce"> <br />
Holy: <input type="text" class="x" id="resHoly"> <br />
Energy: <input type="text" class="x" id="resEnergy"> <br />
Physic: <input type="text" class="x" id="resPhysic"> <br />
Earth: <input type="text" class="x" id="resEarth"> <br />
Death: <input type="text" class="x" id="resDeath"> <br />
<button type="button" onclick="calc()">Oblicz</button>
</form>
<p id="result"></p>
</center>
And super extra code I really wanted to work few days ago:
var button = document.getElementById("button");
function click(){
document.getElementById("content").innerHTML = calc();
};
const final1 = [
"Flame",
"Wound",
"Poison",
"Freeze",
"Curse",
"Divine",
"Zap",
];
function calc() {
var wynik = document.getElementById("mobHp") * 0.05 * document.getElementsByTagName("textarea").value / 100
if (document.getElementsByTagName("textarea").value === 0){
return "Potwor posiada calkowita odpornosc na ", final1;
}
if (document.getElementsByTagName("textarea").value === 100) {
return "Neutralny na ", final1, ", otrzyma ", wynik, " obrazen.";
}
if (document.getElementsByTagName("textarea").value > 100){
return "Wrazliwy na ", final1, ", otrzyma", wynik, " obrazen.";
}
if ((document.getElementsByTagName("textarea").value < 100) || (document.getElementsByTagName("textarea").value > -100)){
return "Czesciowo odporny na ", final1, ", otrzyma", wynik, " obrazen.";
}
else {
return "Nie podales normalnych wartosci.";
}
};

Create a list with key-value pair which contains the id of input element as key and value as the text to display and loop that list.
Below is the code:
let data = {"resFire" : "Flame dmg",
"resIce": "Freeze dmg", "resHoly": "Divine dmg", "resEnergy": "Zap dmg","resPhysic": "Wound dmg", "resEarth": "Poison dmg", "resDeath":
"Curse dmg"}
function calc() {
var tekstPisany = ""
var hp = document.getElementById("hpMob").value;
tekstPisany += "potwor posiada: " + document.getElementById("hpMob").value + "<br>";
for (var key in data){
tekstPisany += data[key] +": " + (hp * 0.05) * document.getElementById(key).value /100 + "<br>";
}
document.getElementById("result").innerHTML = tekstPisany;
}
<form> <center>
HP Moba: <input type="text" class="hp" id="hpMob"><br /><br />
Fire: <input type="text" class="x" id="resFire"> <br />
Ice: <input type="text" class="x" id="resIce"> <br />
Holy: <input type="text" class="x" id="resHoly"> <br />
Energy: <input type="text" class="x" id="resEnergy"> <br />
Physic: <input type="text" class="x" id="resPhysic"> <br />
Earth: <input type="text" class="x" id="resEarth"> <br />
Death: <input type="text" class="x" id="resDeath"> <br />
<button type="button" onclick="calc()">Oblicz</button>
</form>
<p id="result"></p>
</center>

This piece of code seems to work and is a cleaner alternative.
How it works:
Creates a HTMLCollection object of classes
Creates an array with name props
Loops through the HTMLCollection.
Adds the heath to the array without any multiplication (via an if statement)
Pushes the other elements to the array in the format specified in your post
Finally, adds the array to the innerHTML of result, joining them with a line break <br />
I hope this helps you! Please bear in mind, I have added no input checking and if health is not specified the code will likely not work correctly. Hopefully this should give you a good base for improvements.
function calc() {
const fields = document.getElementsByClassName("x");
const props = [];
for (let i = 0; i < fields.length; i++) {
if (fields.item(i).id === "Potwor posiada") {
props.push(`${fields.item(i).id}: ${fields.item(i).value}`);
} else {
props.push(`${fields.item(i).id} dmg: ${(a[0] * fields.item(i).value) / 100}`);
}
}
document.getElementById("result").innerHTML = props.join("<br />");
};
<form> <center>
HP Moba: <input type="text" class="x" id="Potwor posiada"/><br /><br />
Fire: <input type="text" class="x" id="Flame"/> <br />
Ice: <input type="text" class="x" id="Freeze"/> <br />
Holy: <input type="text" class="x" id="Divine"/> <br />
Energy: <input type="text" class="x" id="Zap"/> <br />
Physic: <input type="text" class="x" id="Wound"/> <br />
Earth: <input type="text" class="x" id="Poison"/> <br />
Death: <input type="text" class="x" id="Curse"/> <br />
<button type="button" onclick="calc()">Oblicz</button>
</form>
<p id="result"></p>
</center>

So what you could do is to make arrays with all of the things you will loop through, so you could reuse the array 'lista', then create another array that is going to have all of the ids of your HTML elements and then you make another array for those text messages you add. Then you would have to make a triple-nested loop to loop through all of the arrays, but to be honest I don't think it's worth it. If I were you, I'd leave it this way, because it's way more readable than nesting loops with separate arrays.
However I can give you 2 tips with your code:
avoid using var . It's depracated and can mess up with the scope for your functions and other variables.
in this extra code you attached you're not returning strings. In the first if statement you have something like this:
return "Potwor posiada calkowita odpornosc na ", final1;
and as I understand, final1 is an array. Point to which element of the array you want to return. Also, use + insead of , in the returned value.
So if you would want to return the monster having resistance to Flame, you should return it this way:
return "Potwor posiada calkowita odpornosc na " + final1[0]
I hope this helped. Greetings from another Polish person :) Pozdro!

Related

Run JavaScript functions when user presses enter

I made a calculator with specific properties in HTML and I would like for the user to be able to press enter to show both of display1() and display2().
In other words, I want the enter key to trigger button Both.
Here is the code I have and what I have tried so far I attempted to add:
<!DOCTYPE html>
<html>
<head>
<title>Square Yards Calculator</title>
</head>
<body>
<div id='calc-contain'>
<form name="calculator">
<input type="text" name="answer" />
<br>
<input type="button" value=" 1 " onclick="calculator.answer.value += '1'" />
<input type="button" value=" 2 " onclick="calculator.answer.value += '2'" />
<input type="button" value=" 3 " onclick="calculator.answer.value += '3'" />
<input type="button" value=" + " onclick="calculator.answer.value += '+'" />
<br/>
<input type="button" value=" 4 " onclick="calculator.answer.value += '4'" />
<input type="button" value=" 5 " onclick="calculator.answer.value += '5'" />
<input type="button" value=" 6 " onclick="calculator.answer.value += '6'" />
<input type="button" value=" - " onclick="calculator.answer.value += '-'" />
</br>
<input type="button" value=" 7 " onclick="calculator.answer.value += '7'" />
<input type="button" value=" 8 " onclick="calculator.answer.value += '8'" />
<input type="button" value=" 9 " onclick="calculator.answer.value += '9'" />
<input type="button" value=" Flex61 " onclick="display1()" />
</br>
<input type="button" value=" c " onclick="calculator.answer.value = '',
document.getElementById('printhere1').innerHTML= '',
document.getElementById('printhere2').innerHTML= ''" />
<input type="button" value=" 0 " onclick="calculator.answer.value += '0'" />
<input type="button" value=" Both " onclick="display1(),display2()" />
<input type="button" value=" Gap55 " onclick="display2()" />
</br>
</form>
<div id="agh">
<p>Enter how many Square yards (SY) you are covering</p>
<p id="printhere1"></p>
<p id="printhere2"></p>
</div>
</div>
<script type="text/javascript">
function display1(){
//Assigning the variable to the user input
var squareyards = eval(calculator.answer.value);
if (squareyards < 0 || squareyards == null){
squareyards = 0
}
var pounds = 5
pounds = squareyards * pounds
// to print the input here
document.getElementById("printhere1").innerHTML = "For "+ squareyards + " SY sou need: "+ pounds + " lbs of Elasto Flex61";
}
function display2(){
//Assigning the variable to the user input
var squareyards = eval(calculator.answer.value);
if (squareyards < 0 || squareyards == null){
squareyards = 0
}
var rolls = 9
rolls = Math.ceil(squareyards * rolls / 103)
// to print the input here
document.getElementById("printhere2").innerHTML = "For "+ squareyards + " SY sou need: "+ rolls + " Rolls of Gap55 Smooth";
}
$(function(){
$(':text').bind('keydown',function(e){ //on keydown for all textboxes
if(e.keyCode==13){ //if this is enter key
e.preventDefault();
e.display1();
e.display2();
}
});
});
</script>
</body>
</html>
You're almost there. It looks like you have a mix of native JavaScript, the document.getElementById stuff and jQuery for the keydown functionality. jQuery's not necessary so I would recommend just using native JavaScript for everything.
So I would refactor this bit:
$(function(){
$(':text').bind('keydown',function(e){ //on keydown for all textboxes
if(e.keyCode==13){ //if this is enter key
e.preventDefault();
e.display1();
e.display2();
}
});
});
To be native JavaScript:
// Capture enter button event on entire page
document.addEventListener('keydown', getAnswer);
// I made it a separate function in case you want to re-use
function getAnswer(e) {
if (e.keyCode==13) { //if this is enter key
e.preventDefault();
display1();
display2();
}
}
Here is a working codepen.
However, this is just the first step to get it working. Like #certainperformance said the next step would be to remove the document.getElementByIds from the "Clear" button onclick and move them to a separate function.
Hope this helps.

Entering multiple records on same HTML page

I am creating a JS form where i need 3 inputs from user and after typing the 3 inputs , on clicking 'Add record' button ,it should display them on the same page one after another (line by line) for every button click. With my code, it is writing every new input entry in the same line and not next line. How do i do it ?
My result:
Andrew Arts 2007 Evelyn Computers 2006
Expected result :
Andrew Arts 2007
Evelyn Computers 2006
function doSubmit() {
document.getElementById('f1').innerHTML += document.myform.name.value + " ";
document.getElementById('f1').innerHTML += document.myform.major.value + " ";
document.getElementById('f1').innerHTML += document.myform.year.value + " ";
return false;
}
<body>
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30" type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<p id='f1'></p>
</body>
You use a <br> tag to break the line inside a <p> tag.
You just have to make a small change in your function :
function doSubmit() {
document.getElementById('f1').innerHTML += document.myform.name.value + " ";
document.getElementById('f1').innerHTML += document.myform.major.value + " ";
document.getElementById('f1').innerHTML += document.myform.year.value + " ";
document.getElementById('f1').innerHTML +='<br />'
return false;
}
If you're looking to style your form values , it would be good to append <p>tag for each form value . It will require a small change like below :
function doSubmit() {
document.getElementById('form-value').innerHTML += '<p>'+ document.myform.name.value + " " + document.myform.major.value + " " + document.myform.year.value + " " + "</p>";
return false;
}
Your HTML :
<body>
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30"
type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<div id="form-value">
</div>
I would suggest creating a new p element for every submitted input. You also don't want to store the user input into the innerHTML, because it can lead to cross-site scripting attacks. To prevent this, you can use innerText instead. Here is an example of how you can achieve all that with your code:
function doSubmit() {
const newInputParagraph = document.createElement("p");
newInputParagraph.innerText += document.myform.name.value + " ";
newInputParagraph.innerText += document.myform.major.value + " ";
newInputParagraph.innerText += document.myform.year.value + " ";
document.getElementById("inputs").appendChild(newInputParagraph);
}
And you need to add container for input results (simple div) to your markup, for example like this:
<form name="myform">
<p>
Name: <input name="name" size="30" type="text" /> course: <input name="major" size="30" type="text" /> Year : <input name="year" size="4" type="text" />
</p>
<input type="button" value="Add record" onClick='doSubmit(); return false' />
</form>
<div id="inputs"></div>

My JQuery script is not retrieving form text values

I'm trying to get the data from a form and use the values for a final result.
The problem is (at least what it looks like when I'm debugging) is no values are being retried and stored in the vars I've created.
Here's the form:
<form>
<p>
<label for="numDigits">Number of Digits: </label>
<input type="text" id="numDigits" name="numDigits" />
</p>
<p>
<label for="num1">First Number: </label>
<input type="text" id="num1" name="num1" />
</p>
<p>
<label for="num2">Second Number: </label>
<input type="text" id="num2" name="num2" />
</p>
<p>
<label for="num3">Third Number: </label>
<input type="text" id="num3" name="num3" />
</p>
<p>
<input type="button" name="calc" id="calc" value="Calculate" />
</p>
<p id="result">Result will be displayed here when the button is pressed.</p>
</form>
and the JQuery script
$("#calc").on('click', function(){
var a = Number($("#numDigits").val());
var x = Number($("#num1").val());
var y = Number($("#num2").val());
var z = Number($("#num3").val());
var total = a * 3 + x + ((a + x - y) % a) + ((a + z - y) % a);
$("#result").html("<p class='id'>" + total + "</p>");
});
Thanks in advance for the help!
Edit: I updated the code to the working version.
Its seems to work well: fiddle
But note that, if you want to manipulate the input as numbers, you should write
var a = Number($("#numDigits").val());
var x = Number($("#num1").val());
var y = Number($("#num2").val());
var z = Number($("#num3").val());
Replace the replaceWith() with html(). I have The DEMO working:
$("#calc").click(function(){
var a = $("#numDigits").val();
var x = $("#num1").val();
var y = $("#num2").val();
var z = $("#num3").val();
var total = a * 3 + x;
total += ((y - x) % a);
total += ((y - z) % a);
$("#result").html(total);
});

Javascript Update Total Sum from Fields

I have created the code using Javascript but I'm getting and error when I hit the calculate button.
the formula im using is this:
A + B + C + D x E% + F =
The error I'm receiving is:
{"error": "Please use POST request"}
The code im using is:
// define a function to perform our calculation.
function calculate() {
// retrieve the values from the amount and percentage fields
// and store them in variables.
var A = $('#A').val();
var B = $('#B').val();
var C = $('#C').val();
var D = $('#D').val();
var E = $('#E').val();
var F = $('#F').val();
// calculation
var total = A + B + C + D * (E / 100) + F;
$('#total').val(total.toFixed(2));
return false;
}
$('#calculator').submit(calculate);
<form id="calculator">
<p>Base:
<input id="A" value="0.00" />
</p>
<p>Rush:
<input id="B" value="0.00" />
</p>
<p>Added:
<input id="C" value="0.00" />
</p>
<p>Extra:
<input id="D" value="0.00" />
</p>
<p>Ship:
<input type ="hidden" id="E" value="5" />
</p>
<p>
<input id="F" value="0.00" />
</p>
<hr />
<p>Total:
<input id="total" disabled="disabled" />
</p>
<p>
<input type="submit" />
</p>
</form>
I have create a plugin to create calculation form called calx, you can download it here
just define data formula in the target element, and initialize calx
<form id="calculator">
<p>Base: <input type="text" id="A" value="0.00" /></p>
<p>Rush: <input type="text" id="B" value="0.00" /></p>
<p>Added: <input type="text" id="C" value="0.00" /></p>
<p>Extra: <input type="text" id="D" value="0.00" /></p>
<p>Ship: <input type ="hidden" id="E" value="5" /></p>
<p><input type="text" id="F" value="0.00" /></p>
<hr />
<p>Total: <input type="text" id="total" disabled="disabled" data-formula="$A + $B + $C + $D * ($E/100) + $F" /></p>
<p><input type="submit" id="calculate" /></p>
</form>
javascript section
$(document).ready(function(){
$('#calculator').calx({autocalculate:false});
$('#calculate').click(function(e){
e.preventDefault();
$('#calculator').calx('update');
});
});
You're getting an unhandled TypeError from the middle of calculate():
$('#total').val(total.toFixed(2));
// TypeError: Object 0.000.000.0000.00 has no method 'toFixed'
With it being thrown, return false; isn't evaluated and the <form> still submits as normal. And, {"error": "Please use POST request"} is JSFiddle's way of refusing to handle the request since it's sent with HTTP GET.
The error is because total, A, B, etc. aren't Numbers and + also concatenates:
var total = A + B + C + D * (E / 100) + F;
// total = "0.00" + "0.00" + ... + "0.00";
<input> values are always Strings, so you'll need to parse them in order to add Numbers rather than concat Strings:
var A = parseFloat($('#A').val());
var B = parseFloat($('#B').val());
var C = parseFloat($('#C').val());
var D = parseFloat($('#D').val());
var E = parseFloat($('#E').val());
var F = parseFloat($('#F').val());
http://jsfiddle.net/wKr3u/
And, while the differences are negligible in most cases, e.preventDefault() (as Jeff Mercado suggested) has one benefit over return false:
It can be used sooner in the event handler, allowing the default action to still be prevented despite an error.
function calculate(ev) {
ev.preventDefault();
// retrieve the values from the amount and percentage fields
// ...
}
assuming that you want it to just calculate the total without actually submitting, you need to stop the submit event from proceeding:
$('#calculator').on('submit', function(ev) {
ev.preventDefault();
calculate();
});
On your code total.toFixed(2) giving this error and by default javascript will take the value as string so You have to handle that to
Update
string to number just do like this
var total = A*1 + B*1 + C*1 + D * (E / 100) + F*1;
HERE IS THE SOLUTION

javascript sum calculation not functioning

I have a cgi form for employees to enter travel expenses. I'm using javascript to automatically display & send calculated data. The first (mileage) calculation on the form works. I cannot get the 2nd (total) calculation to appear. The result I am looking for is-
Miles * Rate (0.555) = Mileage (works)
MileageExp + other input fields = TotalExpenses (not working)
Here is the javascript-
<script type="text/javascript">
function totalexpense()
{
//mileage
a = document.event.Miles.value
b = document.event.Rate.value
c = a * b
z = c
document.event.Mileage.value = c.toFixed(2)
//total
d = document.event.Parking.value
e = document.event.Tolls.value
f = document.event.Plane.value
g = document.event.Train.value
h = document.event.Bus_Taxi.value
i = document.event.Lodging.value
j = document.event.Food.value
k = document.event.Other.value
l = z + d + e + f + g + h + i + j + k
document.event.Total_Expenses.value = l.toFixed(2)
}
</script>
The browser says there is an error in the document.event.Total_Expenses.value = l.toFixed(2) line.
HTML-
<p align="left" class="bold"><span class="style8">Mileage:</span><br>
Miles:
<input name="Miles" size="10">
X rate:
<input name="Rate" size="10" value="0.555" onblur="totalexpense();">
=
<input name="Mileage" size="10" readonly=true>
</p>
<p align="left">Parking:</span><br>
<input name="Parking" size="10" onblur="totalexpense();">
</p>
<p align="left">Tolls:</span><br>
<input name="Tolls" size="10" onblur="totalexpense();">
</p>
<p align="left">Airline Tickets:</span><br>
<input name="Plane" size="10" onblur="totalexpense();">
</p>
<p align="left">Train:</span><br>
<input name="Train" size="10" onblur="totalexpense();" >
</p>
<p align="left">Bus/Taxi:</span><br>
<input name="Bus_Taxi" size="10" onblur="totalexpense();" >
</p>
<p align="left">Lodging:</span><br>
<input name="Lodging" size="10" onblur="totalexpense();" >
Accomodations with- <input name="Accomodations_With" type="text" size="40" />
</p>
<p align="left" class="bold"><span class="style8">Food/Beverage:</span><br>
<input name="Food" size="10" onblur="totalexpense();" >
</p>
<p align="left">Other Expenses:</span><br>
<input name="Other" size="10" onblur="totalexpense();" >
</p>
<p align="left" class="bold"><span class="style8">Other Expense Notes:</span><br>
<span class="main style22">
<textarea name="Other_Expense_Notes" cols="50" rows="3" class="fieldbkgrd"></textarea>
</span>
</p>
<h3>Total Expenses:<br>
<input name="Total_Expenses" size="10" READONLY>
You need to convert the values from strings to numbers - .toFixed only works on a number.
document.event.Total_Expenses.value = Number(l).toFixed(2);
The reason your code worked with the mileage is because the 0.555 was cast to an integer in:
c = a * b; (c = # * 0.555)
You then do the "addition" which was treated like a concatenation:
z + d + e + f + g + h + i + j + k;
This converted the int to a string. Thus:
document.event.Total_Expenses.value = l.toFixed(2);
failed because the type cast was now a string.
If you want to convert a value explicitly then you need to use parseInt();
d = parseInt(document.event.Parking.value);
You need to convert the values from strings to numbers - .toFixed only works on a number.
document.event.Total_Expenses.value = Number(l).toFixed(2);
<input name="Total_Expenses" size="10" READONLY>
you set it as read only so you cannot set a value to read only elements, that's my best guess

Categories

Resources