Run JavaScript functions when user presses enter - javascript

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.

Related

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

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!

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>

Dynamic add multi fields in javascript

I am beginner in javascript. I need to dynamic add multifields in existing form that have same id.
first fields has this name :
<input type="text" name="myInputs[0][address]">
<input type="text" name="myInputs[0][whitelist]">
And when clicking "Add another text input" I want a new fields with
<input type="text" name="myInputs[1][address]">
<input type="text" name="myInputs[1][whitelist]">
and clicking again on "Add another text input"
<input type="text" name="myInputs[2][address]">
<input type="text" name="myInputs[2][whitelist]">
When submit post only the first fields are posted :
<input type="text" name="myInputs[0][address]">
<input type="text" name="myInputs[0][whitelist]">
Here the code :
<script>
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs["+ (counter + 1) +"][address]'><input type='text' name='myInputs["+ (counter + 1) +"][whitelist]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
</script>
<div id="dynamicInput">
Entry 1<br>
<input type="text" name="myInputs[0][address]">
<input type="text" name="myInputs[0][whitelist]">
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');">

I have a form with the submit button linked to javascript function but nothing is happening when I click the submit button

I'm trying to make a form which when I click the submit button will send the information from the form fields to a javascript function and then show the results to the user. I've made something like this before that's very similar and works fine, but for some reason this isn't doing anything when I click submit. I must have missed something. Here's the code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" >
<title>Javascript Form</title>
</head>
<body>
<form id="formID" name="myform" action="" method="get">
Customer Name:
<input type="text" name="names" value="">
<br/>
Street Address:
<input type="text" name="street" value="">
<br/>
City:
<input type="text" name="city" value="">
<br/>
State:
<input type="text" name="state" value="">
<br/>
Zip Code:
<input type="text" name="zip" value="">
<br/>
Beginning Odometer Reading:
<input type="text" name="beginO" value="">
<br/>
Ending Odometer Reading:
<input type="text" name="edinO" value="">
<br/>
Number of Days Car was Used:
<input type="text" name="days" value="">
<br/>
<input type="button" name="button" value="Submit" onClick="car(this.form)">
</form>
<script type="text/javascript">
function car(form) {
var names = form.names.value;
var street = form.street.value;
var city = form.city.value;
var state = form.state.value;
var zip = form.zip.value;
var beginO = form.beginO.value;
var endO = form.endO.value;
var days = form.days.value;
var miles = endO - beginO;
var charge = days * 15 + miles * 0.12;
alert("Miles driven: " + miles + ". Charge: " + charge + ". Name: " + names + ". Address : " + street + " , " + city + " " + state + " " + zip + ". ");
}
</script>
</body>
</html>
It's because you have a JavaScript error at this line:
var endO = form.endO.value;
You have a typo in your form element name:
<input type="text" name="edinO" value="">
form.endO is undefined, so getting value throws an error.

jQuery: Verify If one of multiple required checkboxes is/are checked

I have a form with multiple groups of checkboxes (among other things). Some of these groups are mandatory fields (At least one checkbox needs to be checked within that group).
I am able to tell if a group has a checkbox checked, but I failed to make them mandatory. Also I am need to get one long string with the values of the selected checkbox(es). I would need to have a string where if the user checks, say the first 3 checkboxes from group1, the string to be:
"zero | 1 val | 2 val"
The code is a simplified version of my original. Here is the jFiddle: http://jsfiddle.net/QyY2P/1/
Also, for your convenience I am also including the code here:
jQuery:
function countChecked() {
//Group 1
var n = $("#group1 input:checked").length;
$("#count").text(n + (n <= 1 ? " is" : " are") + " checked!");
$("#group1 input:checked").each(function() {
txt += ($(this).val() + " | ");
$("#selection1").text(txt);
alert($(this).val() + " | ");
});
//Group 2
var n = $("#group2 input:checked").length;
$("#count").text(n + (n <= 1 ? " is" : " are") + " checked!");
$("#group2 input:checked").each(function() {
txt += ($(this).val() + " | ");
$("#selection3").text(txt);
alert($(this).val() + " | ");
});
}
countChecked();
$(":checkbox").click(countChecked);
HTML:
<form>
<div id="group1">
<p> *Please select a box (Mandatory)</p>
<input type="checkbox" name="ckb_unit[]" value="zero" />
<input type="checkbox" name="ckb_unit[]" value="1 val" />
<input type="checkbox" name="ckb_unit[]" value="2 val" />
<input type="checkbox" name="ckb_unit[]" value="3 val" />
<input type="checkbox" name="ckb_unit[]" value="4 val" />
</div>
<div id="group2">
<p>Please select a box</p>
<input type="checkbox" name="ckb_unit[]" value="zero" />
<input type="checkbox" name="ckb_unit[]" value="A" />
<input type="checkbox" name="ckb_unit[]" value="B" />
<input type="checkbox" name="ckb_unit[]" value="C" />
<input type="checkbox" name="ckb_unit[]" value="D" />
</div>
<div id="group3">
<p>*Please select a box (Mandatory)</p>
<input type="checkbox" name="ckb_unit[]" value="zero" />
<input type="checkbox" name="ckb_unit[]" value="1 A" />
<input type="checkbox" name="ckb_unit[]" value="2 B" />
<input type="checkbox" name="ckb_unit[]" value="3 C" />
<input type="checkbox" name="ckb_unit[]" value="4 D" />
</div>
</form>
<!-- For debugging purposes -->
<br/>
<div id="count"></div>
<div id="selection1"></div>
<div id="selection3"></div>
PS. I am a beginner, perhaps you noticed it by my not so elegant coding >_<
You can make it mandatory by checking if n is 0 when the user hits submit and then attracting the user's attention towards it somehow (appending an error message, for example). I'm talking about this n:
var n = $("#group1 input:checked").length;
Looking at JSFiddle, it seems you didn't declare txt as a variable, so this works for me:
//Group 1
var txt = ""; // initialise txt with an empty string, so you can append to it later
var n = $("#group1 input:checked").length;
$("#count").text(n + (n <= 1 ? " is" : " are") + " checked!");
$("#group1 input:checked").each(function() {
txt += ($(this).val() + " | ");
$("#selection1").text(txt);
alert($(this).val() + " | ");
});

Categories

Resources