I was trying to make a simple form that allows the user to add two numbers and I want it to show the total number once both of them are added without clicking any button or without page refresh
function add_number() {
var first_number = parseInt(document.getElementById("Text1").value);
var second_number = parseInt(document.getElementById("Text2").value);
var result = first_number + second_number;
document.getElementById("txtresult").value = result;
}
<p>Enter First Number :</p>
<br>
<input type="text" id="Text1" name="TextBox1">
<br> <p>Enter Second Number :</p>
<br>
<input type="text" id="Text2" name="TextBox2">
<br>Result :
<br>
<input type="text" id="txtresult" name="TextBox3">
I tried the above code but it is not working.
I was writing this as #TylerRoper and #kshetline made their useful comments, so I've incorporated them. Fundamentally what was needed was to add the event handler. I've also included a check for the parse failing so that you get a result even if one field is empty or non-numeric (it's treated as 0).
var text1 = document.getElementById("Text1");
var text2 = document.getElementById("Text2");
function add_number() {
var first_number = parseFloat(text1.value);
if (isNaN(first_number)) first_number = 0;
var second_number = parseFloat(text2.value);
if (isNaN(second_number)) second_number = 0;
var result = first_number + second_number;
document.getElementById("txtresult").value = result;
}
<p>Enter First Number :</p>
<br>
<input type="text" id="Text1" name="TextBox1" oninput="add_number()">
<br> <p>Enter Second Number :</p>
<br>
<input type="text" id="Text2" name="TextBox2" oninput="add_number()">
<br>Result :
<br>
<input type="text" id="txtresult" name="TextBox3">
Good solution provided by #Nick. I just added a check that user can enter only numeric input. An alternative approach.
function add_number(e) {
if (isNumberKey(e)) {
setTimeout(() => {
var first_number = document.getElementById("Text1").value !== "" ? parseInt(document.getElementById("Text1").value) : 0;
var second_number = document.getElementById("Text2").value !== "" ? parseInt(document.getElementById("Text2").value) : 0;
var result = first_number + second_number;
document.getElementById("txtresult").value = result;
}, 50)
return true;
} else {
return false;
}
}
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
<p>Enter First Number : <input type="text" id="Text1" name="TextBox1" onkeypress="return add_number(event)"></p>
<p>Enter Second Number : <input type="text" id="Text2" name="TextBox2" onkeypress="return add_number(event)"></p>
<br>Result : <input type="text" id="txtresult" name="TextBox3">
Hope it will help you.
jQuery approach:
$('#Text1, #Text2').on("paste keyup",
function () {
var result = parseInt($("#Text1").val()) + parseInt($("#Text2").val());
$("#txtresult").val((isNaN(result) ? '' : result));
}
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Enter First Number:</p>
<input type="text" id="Text1" name="TextBox1">
<p>Enter Second Number:</p>
<input type="text" id="Text2" name="TextBox2">
<p>Result:</p>
<input type="text" id="txtresult" name="TextBox3">
function add_number() {
var first_number = parseInt(document.getElementById("Text1").value);
var second_number = parseInt(document.getElementById("Text2").value);
var result = first_number + second_number;
document.getElementById("txtresult").value = result;
}
<p>Enter First Number :</p>
<br>
<input type="text" id="Text1" name="TextBox1">
<br> <p>Enter Second Number :</p>
<br>
<input type="text" id="Text2" name="TextBox2">
<br>Result :
<br>
<input type="text" id="txtresult" name="TextBox3">
<p>
<input type="button" value="submit" onclick="add_number()">
<input type="reset" value="reset">
Related
I was just trying to write a simple javascript program that will demonstrate to take user input from text field, and clicking the button will display the summation result of those number in a paragraph. But unfortunately the below code is not working. Clicking the button shows NAN in the Paragraph.
<input type="text" name="" id="num1"><br><br>
<input type="text" name="" id="num2"><br> <br>
<button id="add">Answer</button>
<br>
<p id="para"></p>
<script>
let num1=parseInt(document.getElementById("num1"));
let num2=parseInt(document.getElementById("num2"));
let add=document.getElementById("add");
add.addEventListener("click",function(){
document.getElementById("para").innerHTML=num1+num2;
});
</script>
You are getting the elementById, but not getting that IDs value.
Add .value on the end of your getElementById
function addTogether()
{
var val1 = document.getElementById('val1').value;
var val2 = document.getElementById('val2').value;
var sum = parseInt(val1) + parseInt(val2);
console.log(sum);
}
<input type="text" id="val1" />
<input type="text" id="val2" />
<input type="button" value="Add Them Together" onclick="addTogether();" />
You can simply do it like this
<input type="text" id="num1"><br><br>
<input type="text" id="num2"><br><br>
<button id="add">Answer</button><br>
<p id="para"></p>
<script>
let add=document.getElementById("add");
add.addEventListener("click",function(){
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
var res = parseInt(num1) + parseInt(num2);
document.getElementById("para").innerHTML = res ;
});
</script>
here is the demo of working code
let add=document.getElementById("add");
add.addEventListener("click",function(){
var num1 = document.getElementById('num1').value;
var num2 = document.getElementById('num2').value;
var res = parseInt(num1) + parseInt(num2);
document.getElementById("para").innerHTML = res ;
});
<input type="text" id="num1"><br><br>
<input type="text" id="num2"><br><br>
<button id="add">Answer</button>
<br>
<p id="para"></p>
you need to get the value of num1 and num2 and you need to get the value after you click -- so inside your function
<input type="text" name="" id="num1"><br><br>
<input type="text" name="" id="num2"><br> <br>
<button id="add">Answer</button>
<br>
<p id="para"></p>
<script>
let add=document.getElementById("add");
add.addEventListener("click",function(){
let num1=parseInt(document.getElementById("num1").value);
let num2=parseInt(document.getElementById("num2").value);
document.getElementById("para").innerHTML=num1+num2;
});
</script>
I am currently working with forms and javascript validation.. i have completed most of my code and am on the last step however cant seem to get it working and not sure what ive done wrong.. spent hours on this last part before i looked for help.
basically a user inputs their information into a form and then when they click submit the information get validated, and the inputed info moves onto a confirmation page.. at the moment the input i put in doesnt get validated anymore and is blank in the confirmation page..
First HTML register page
<form id="regform" method="post" action="confirm.html"
novalidate="novalidate">
<fieldset id="person">
<legend>Your details:</legend>
<p><label for="firstname">Enter your first name</label>
<input type="text" name="firstname" id="firstname" size="20"
/>
</p>
<p><label for="lastname">Enter your last name</label>
<input type="text" name="lastname" id="lastname" size="20" />
</p>
<fieldset id="species">
<legend>Species:</legend>
<label for="human">Human</label>
<input type="radio" name="species" id="human"
value="Human"/><br />
<label for="dwarf">Dwarf</label>
<input type="radio" name="species" id="dwarf"
value="Dwarf" /><br />
<label for="elf">Elf</label>
<input type="radio" name="species" id="elf"
value="Elf" /><br />
<label for="hobbit">Hobbit</label>
<input type="radio" name="species" id="hobbit"
value="Hobbit" /><br />
</fieldset>
<p><label for="age">Enter your age</label>
<input type="text" id="age" name="age" size="5">
</p>
</fieldset>
<fieldset id="trip">
<legend>Your trip:</legend>
<fieldset>
<legend>Booking:</legend>
<label for="1day">1 Day Tour - $200 </label>
<input type="checkbox" name="1day" id="1day"
value="1day" /><br />
<label for="4day">4 Day Tour - $1500</label>
<input type="checkbox" name="4day" id="4day"
value="4day" /><br />
<label for="10day">10 Day Tour - $3000</label>
<input type="checkbox" name="10day" id="10day"
value="10day" /><br />
</fieldset>
<p>
<label for="food">Menu preferences</label>
<select name="food" id="food">
<option value="none">Please select</option>
<option value="lembas">Lembas</option>
<option value="mushrooms">Mushrooms</option>
<option value="ent">Ent Draft</option>
<option value="cram">Cram</option>
</select>
</p>
<p>
<label for="partySize">Number of Travellers</label>
<input type="text" id="partySize" name="partySize" maxlength="3"
size="3" />
</p>
</fieldset>
<div id="bottom"> </div>
<p><input type="submit" value="Book Now!" />
<input type="reset" value="Reset" />
</p>
Validation for Javascript
function validate() {
var errMsg = "";
var result = true;
var firstname = document.getElementById("firstname").value;
var lastname = document.getElementById("lastname").value;
if (!firstname.match(/^[a-zA-Z]+$/)) {
errMsg = errMsg + "Your first name must only contain alpha characters\n";
result = false;
}
if (!lastname.match(/^[a-zA-Z+$]/)) {
errMsg = errMsg + "Your last name must only contain alpha characters\n";
result = false;
}
var age = document.getElementById("age").value;
if (isNaN(age)) {
errMsg = errMsg + "your age must be a number\n";
result = false;
}
else if (age < 18) {
errMsg = errMsg + " your age must be 18 or older\n";
result = false;
}
else if (age >= 10000) {
errMsg = errMsg + "your age must be between 18 and 10000\n";
result = false;
}
else {
var tempMsg = checkSpeciesAge(age);
if (tempMsg != "") {
errMsg + tempMsg;
result = false;
}
var partySize = document.getElementById("partySize").value;
if (isNaN(partySize)) {
errMsg = errMsg + "your age must be a number\n";
result = false;
}
else if (partySize < 1) {
errMsg = errMsg + " party size must be greater than 0\n";
result = false;
}
else if (age >= 100) {
errMsg = errMsg + "your party size must be less or equal to 100\n";
result = false;
}
}
var is1day = document.getElementById("1day").checked;
var is4day = document.getElementById("4day").checked;
var is10day = document.getElementById("10day").checked;
if (!(is1day || is4day || is10day)) {
errMsg = errMsg + "please select at least one trip.\n";
result = false;
}
if (document.getElementById("food").value == "none") {
errMsg = errMsg + "You must select a food preference. \n ";
result = false;
}
var human = document.getElementById("human").checked;
var dwarf = document.getElementById("dwarf").checked;
var elf = document.getElementById("elf").checked;
var hobbit = document.getElementById("hobbit").checked;
if (!(human || dwarf || elf || hobbit)) {
errMsg = errMsg + "please select a spiecies";
result = false;
}
if (errMsg !== "") {
alert(errMsg);
}
if (result) {
storeBooking(firstname, lastname, age, species, is1day, is4day, is10day);
}
return result;
}
function getSpecies() {
var speciesName = "Unknown";
var speciesArray = document.getElementById("species").getElementsByTagName("input");
for (var i = 0; i < speciesArray.length; i++){
if (speciesArray[i].checked)
speciesName = speciesArray[i].value;
}
return speciesName;
}
function checkSpeciesAge(age) {
var errMsg = "";
var species = getSpecies();
switch(species){
case "human":
if (age > 120) {
errMsg = "you cannot be a Human and over 120. \n";
}
break;
case "dwarf":
case "hobit":
if (age > 150 ){
errMsg = " YOu can not be a " + species + " and over 150 .\n ";
}
break;
case "elf":
break;
default:
errMsg = " we dont allow your kind on our tours. \n";
}
return errMsg;
}
function storeBooking(firstname, lastname, age, species, is1day, is4day, is10day){
var trip= "";
if(is1day) trip ="1day";
if(is4day) trip +=", 4day";
is(is10day) trip += ", 10day";
sessionStorage.trip = trip;
sessionStorage.firstname= firstname;
sessionStorage.lastname= lastname;
sessionStorage.age = age;
sessionStorage.species= species;
sessionStorage.partySize= partySize;
sessionStorage.food = food;
alert ("Trip stored: " + sessionStorage.trip);
}
function init() {
var regForm = document.getElementById("regform");
regForm.onsubmit = validate;
}
window.onload = init;
Confirm HTML
<form id="bookform">
<fieldset>
<legend>Your Booking</legend>
<p>Your Name: <span id="confirm_name"></span></p>
<p>Species: <span id="confirm_species"></span></p>
<p>Age: <span id="confirm_age"></span></p>
<p>Trips booked: <span id="confirm_trip"></span></p>
<p>Food Preference: <span id="confirm_food"></span></p>
<p>Number of beings: <span id="confirm_partySize"></span></p>
<p>Total Cost: $<span id="confirm_cost"></span></p>
<input type="hidden" name="firstname" id="firstname" />
<input type="hidden" name="lastname" id="lastname" />
<input type="hidden" name="age" id="age" />
<input type="hidden" name="species" id="species" />
<input type="hidden" name="trip" id="trip" />
<input type="hidden" name="food" id="food" />
<input type="hidden" name="partySize" id="PartySize" />
<input type="hidden" name="cost" id="cost" />
<p><label for="date">Preferred Date</label>
<input type="text" id="date" name="bookday" required="required" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" title="Format dd/mm/yyyy" maxlength="10" size="10" />
</p>
<input type="submit" value="Confirm Booking" />
<button type="button" id="cancelButton">Cancel</button>
</fieldset>
Javascrips file 2 to bring the info over to the confirmation
function validate(){
var errMsg = "";
var result = true;
return result;
function calcCost(trips, partySize){
var cost = 0;
if (trips.search("1day") != -1) cost = 200;
if (trips.search("4day")!= -1) cost += 1500;
if (trips.search("10day")!= -1) cost += 3000;
return cost * partySize;
}
function getBooking(){
var cost = 0;
if(sessionStorage.firstname != undefined){
//confirmation text
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_age").textContent =sessionStorage.age;
document.getElementById("confirm_trip").textContent = sessionStorage.trip;
document.getElementById("confirm_species").textContent = sessionStorage.species;
document.getElementById("confirm_food").textContent =sessionStorage.food;
document.getElementById("confirm_partySize").textContent = sessionStorage.partySize;
cost = calcCost(sessionStorage.trip, sessionStorage.partySize);
document.getElementById("confirm_cost").textContent = cost;
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("age").value = sessionStorage.age;
document.getElementById("species").value = sessionStorage.species;
document.getElementById("food").value = sessionStorage.food;
document.getElementById("partySize").value = sessionStorage.partySize;
document.getElementById("cost").value = cost;
}
}
function init () {
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validate;
}
window.onload = init;
There are a couple of syntax errors that should be clearly visible when you open your browser console:
- errMsg + tempMsg; is not a complete statement,
- is(is10day) trip += ", 10day"; is not valid, and
- storeBooking doesn't have a parameter called partySize
I see a couple of logic errors too:
- checkSpeciesAge will never return an empty string as validate expects, and
- the section of code that attempts to validate partySize has several errors (including that this entire structure is nested inside the age-validation section's else block.)
A few console.log statements could go a long way toward identifying where your variables contain values that you don't expect if there are still bugs to track down after correcting these issues. Good luck!
I tried to fix this, and make some changes in your code. according to your requirement
follow the link of jsfiddle; https://jsfiddle.net/dupinderdhiman/vno15jku/32/
<form id="bookform">
<fieldset>
<legend>Your Booking</legend>
<p>Your Name: <span id="confirm_name"></span></p>
<p>Species: <span id="confirm_species"></span></p>
<p>Age: <span id="confirm_age"></span></p>
<p>Trips booked: <span id="confirm_trip"></span></p>
<p>Food Preference: <span id="confirm_food"></span></p>
<p>Number of beings: <span id="confirm_partySize"></span></p>
<p>Total Cost: $<span id="confirm_cost"></span></p>
<input type="hidden" name="firstname" id="firstname" />
<input type="hidden" name="lastname" id="lastname" />
<input type="hidden" name="age" id="age" />
<input type="hidden" name="species" id="species" />
<input type="hidden" name="trip" id="trip" />
<input type="hidden" name="food" id="food" />
<input type="hidden" name="partySize" id="PartySize" />
<input type="hidden" name="cost" id="cost" />
<p><label for="date">Preferred Date</label>
<input type="text" id="date" name="bookday" required="required" placeholder="dd/mm/yyyy" pattern="\d{1,2}/\d{1,2}/\d{4}" title="Format dd/mm/yyyy" maxlength="10" size="10" />
</p>
<input type="submit" value="Confirm Booking"/>
<button type="button" id="cancelButton">Cancel</button>
</fieldset>
<script>
sessionStorage.trip = "4day";
sessionStorage.firstname= "firstname";
sessionStorage.lastname= "lastname";
sessionStorage.age = 21;
sessionStorage.species= "species";
sessionStorage.partySize= 10;
sessionStorage.food = "food";
function validate(){
var errMsg = "";
var result = true;
return result;
}
function calcCost(trips, partySize){
var cost = 0;
if (trips.search("1day") != -1) cost = 200;
if (trips.search("4day")!= -1) cost += 1500;
if (trips.search("10day")!= -1) cost += 3000;
return cost * partySize;
}
function loadDataFromSession(){
var cost = 0;
if(sessionStorage.firstname != undefined){
//confirmation text
document.getElementById("confirm_name").textContent = sessionStorage.firstname + " " + sessionStorage.lastname;
document.getElementById("confirm_age").textContent =sessionStorage.age;
document.getElementById("confirm_trip").textContent = sessionStorage.trip;
document.getElementById("confirm_species").textContent = sessionStorage.species;
document.getElementById("confirm_food").textContent =sessionStorage.food;
document.getElementById("confirm_partySize").textContent = sessionStorage.partySize;
cost = calcCost(sessionStorage.trip, sessionStorage.partySize);
document.getElementById("confirm_cost").textContent = cost;
//fill hidden fields
document.getElementById("firstname").value = sessionStorage.firstname;
document.getElementById("lastname").value = sessionStorage.lastname;
document.getElementById("age").value = sessionStorage.age;
document.getElementById("species").value = sessionStorage.species;
document.getElementById("food").value = sessionStorage.food;
document.getElementById("partySize").value = sessionStorage.partySize;
document.getElementById("cost").value = cost;
}
}
function init () {
loadDataFromSession();
var bookForm = document.getElementById("bookform");
bookForm.onsubmit = validate;
}
window.onload = init;
</script>
so what is the major change:
Created one function loadDataFromSession which call on init();
remove code from getBooking() add to loadDataFromSession.
now click on submit and your form will be submit
function multiplyBy()
{
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
num3= document.getElementById("result").value = num1 * num2;
document.getElementById("total").value = +num3 ;
}
1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value="" onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p>
<p>Total :<br>
<input type="text" name="total" id="total" value=""/>
</p>
function multiplyBy()
{
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
num3= document.getElementById("result").value = num1 * num2;
}
1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value=""
onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p>
I am multiplying two numbers here.how to add those multiplied numbers in another text box.suppose 2&5 are multiplied later 4&6 multiplied how to add those numbers.
Try this. You need to parse the input value using parseFloat. This will convert the string to a number. The existing result value is added to the newly calculating value. |0 is used for the false value of input getting 0
Updated
prev, present and total result box were added
Append each additional input with new result.
var last=0;
function multiplyBy() {
var num1 = document.getElementById("firstNumber");
var num2 = document.getElementById("secondNumber");
var prev = document.getElementById("prev");
var present = document.getElementById("present");
var total = document.getElementById("result");
prev.value=last;
present.value=(parseFloat(num1.value) * parseFloat(num2.value))
last = last+(parseFloat(num1.value) * parseFloat(num2.value))
total.value=last;
num1.value = "";
num2.value = "";
}
1st Number : <input type="text" id="firstNumber" value="" /><br> 2nd Number: <input type="text" id="secondNumber" value="" onchange="multiplyBy()" /><br>
<p >
Prev result:<br>
<input type="text" name="result" id="prev" ><br>
Present:<br>
<input type="text" name="result" id="present" ><br>
The total Result is : <br>
<input type="text" name="result" id="result"><br>
</p>
You just need for get value of text box and add it with result
function multiplyBy()
{ var sum = 0;
var num=0;
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
num =parseInt(num1 * num2);
num3=parseInt(document.getElementById("result").value);
document.getElementById("result").value=(num + num3);
}
</script>
1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" value=""
onchange="multiplyBy()" /><br>
<p>The Result is : <br>
<input type="text" name="result" id = "result" value="0"/>
</p>
I have added the multiplyBy() to both the input fields and changed the type to number to restrict the user to enter number only.
Please check the code snippet below.
document.getElementById("firstNumber").addEventListener("change",multiplyBy);
document.getElementById("secondNumber").addEventListener("change",multiplyBy);
function multiplyBy()
{
actualResult = document.getElementById("actualResult").value ? document.getElementById("actualResult").value : 0; // Return zero if there is no value in actualResult input field
num1 = document.getElementById("firstNumber").value;
num2 = document.getElementById("secondNumber").value;
num3= document.getElementById("result").value = num1 * num2;
document.getElementById("actualResult").value = Number(actualResult) + num3;
}
1st Number : <input type="number" id="firstNumber" value=""/><br>
2nd Number: <input type="number" id="secondNumber" value=""/><br>
<p>The Current Result is : <br>
<input type="number" name="result" id = "result" value=""/>
</p>
<p>Previous Result + Current Result : <br>
<input type="number" name="actualResult" id = "actualResult" value=""/>
</p>
You need to add event handlers if you want to calculate on change of textbox input like following.
function multiplyBy()
{
var result = document.getElementById("result");
var num1 = document.getElementById("firstNumber").value;
var num2 = document.getElementById("secondNumber").value;
var num3= parseFloat(num1) * parseFloat(num2);// to convert entered values to float and || 0 to use 0 if no value is there
if(!isNaN(num3)){
document.getElementById("resultPrev").value = document.getElementById("result").value;
document.getElementById("resultCurrent").value = num3;
result.value = parseFloat(result.value || 0) + num3;
}
}
document.getElementById("firstNumber").addEventListener("change",multiplyBy);
document.getElementById("secondNumber").addEventListener("change",multiplyBy);
1st Number : <input type="text" id="firstNumber" value="" /><br>
2nd Number: <input type="text" id="secondNumber" /><br>
<p>The Previous Result is : <br>
<input type="text" name="resultPrev" id = "resultPrev" value="0"/>
</p>
<p>The Current Result is : <br>
<input type="text" name="resultCurrent" id = "resultCurrent" value=""/>
</p>
<p>The Final Result is : <br>
<input type="text" name="result" id = "result" value=""/>
</p>
Consider handling non number values.
I have a site I'm working on where I have made a javascript calculator and I need all 3 forms in the page to round to 2. I have used toFixed(2) on my first form. The other 2 forms still display all decimal points even though I have used .toFixed(2) on them. Any ideas
<script type="text/Javascript">
// Begin calculations
function resetCalc() {
document.forms[0].elements[1]="";
}
function calcRect() {
if(validNumber(document.getElementById('length'), 'length') == true) {
if(validNumber(document.getElementById('width'), 'width') == true) {
var length = (document.getElementById('length').value)
var width = (document.getElementById('width').value)
var prodRect = ( length * width / 9 ) .toFixed(2)
document.getElementById('ansRect').value = prodRect
}
}
}
function calcCirc() {
if(validNumber(document.getElementById('diameter'), 'diameter') == true) {
var diameter = (document.getElementById('diameter').value)
var prodCirc = (diameter / 2) * (diameter / 2) * 3.14 /9 .toFixed(2)
document.getElementById('ansCirc').value = prodCirc
}
}
function calcTria() {
if(validNumber(document.getElementById('base'), 'base') == true) {
if(validNumber(document.getElementById('height'), 'height') == true) {
var base = (document.getElementById('base').value)
var height = (document.getElementById('height').value)
var prodTria = (base * .5) * height / 9 .toFixed(2)
document.getElementById('ansTria').value = prodTria
}
}
}
// End Calculations
// BEGIN Validate Values entered
//Requires field that contians value being evaluated
function validNumber(varInput, fieldName) {
if (varInput.value == null) {
alert('Please enter a value for the ' + fieldName + ' field');
varInput.focus();
return false;
}
if (IsNumeric(varInput.value) == false) {
alert('Please enter only numbers or decimal points in the ' + fieldName + ' field');
varInput.focus();
return false;
}
return true;
}
// END Validation
// check for valid numeric strings
function IsNumeric(strString) {
var strValidChars = "0123456789.";
var strChar;
var blnResult = true;
if (strString.length == 0) return false;
// test strString consists of valid characters listed above
for (i = 0; i < strString.length && blnResult == true; i++)
{
strChar = strString.charAt(i);
if (strValidChars.indexOf(strChar) == -1)
{
blnResult = false;
}
}
return blnResult;
}
//
</script>
And the html
<form name="sodCalc" id="formEnquire" action="">
<div id="ctl00_body_sodCalc1_validationSummarySodCalc" style="color:Red;display:none;"> </div>
<p><strong>For a rectangular shaped area</strong></p>
<p>
<label>Length</label>
<input name="length" id="length" type="text" tabindex="1" />
<label>Width</label>
<input name="width" id="width" type="text" tabindex="1" />
<label>Result</label>
<input type="text" value="0" name="ansRect" id="ansRect" />
<br class="clear"/>
<input type="button" value="Calculate" onclick="calcRect()" name="btnRect" id="btnRect" />
<input type="reset" value="Reset" onclick="resetCalc()" name="reset" id="reset" />
</p>
</form>
<form name="sodCalc" id="formEnquire" action="">
<div id="ctl00_body_sodCalc1_validationSummarySodCalc" style="color:Red;display:none;"> </div>
<p><strong>For a circle area </strong></p>
<p>
<label>Diameter Of Circle</label>
<input name="diameter" id="diameter" type="text" tabindex="1" />
<label>Result</label>
<input type="text" size="6" value="0" name="ansCirc" id="ansCirc" />
<br class="clear"/>
<input type="button" value="Calculate" onclick="calcCirc()" name="btnCirc" id="btnCirc" />
<input type="reset" value="Reset" onclick="resetCalc()" name="reset" id="reset" />
` </p>
</form>
<form name="sodCalc" id="formEnquire" action="">
<div id="ctl00_body_sodCalc1_validationSummarySodCalc" style="color:Red;display:none;"> </div>
<p><strong>For a triangle area </strong></p>
<p>
<label>Base</label>
<input name="base" id="base" type="text" tabindex="1" />
<label>Height</label>
<input name="height" id="height" type="text" tabindex="1" />
<label>Result</label>
<input type="text" size="6" value="0" name="ansTria" id="ansTria" />
<br class="clear"/>
<input type="button" value="Calculate" onclick="calcTria()" name="btnTria" id="btnTria" />
<input type="reset" value="Reset" onclick="resetCalc()" name="reset" id="reset" />
</p>
</form>
You need to parenthesize the expressions in the second two functions like you did in the first one:
var prodTria = ( (base * .5) * height / 9 ).toFixed(2)
Without the extra parentheses, all that was being converted in that one was the 9.
i want to show the money that customer must pay and my inputs are like this :
<input type="text" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" class="form-control" placeholder="quantity" id="txt" name="limit">
when the input text is changing i want to show the total cost (quantity*cost) in a <p> tag Dynamicly how can it be with javascript?
You can try this:
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" onchange="calculate()">
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" onchange="calculate()">
<p id="result"></p>
And javascript part:
function calculate() {
var cost = Number(document.getElementById("credit"));
var limit = Number(document.getElementById("limit"));
document.getElementById("result").innerHTML= cost*limit;
}
You must ensure you entered numbers in inputs.
All of the above will generate errors if both the boxes are blank . Try this code , its tested and running .
<script>
function calc()
{
var credit = document.getElementById("credit").value;
var limit = document.getElementById("limit").value;
if(credit == '' && limit != '')
{
document.getElementById("cost").innerHTML = parseInt(limit);
}
else if(limit == '' && credit != '')
{
document.getElementById("cost").innerHTML = parseInt(credit);
}
else if(limit!= '' && credit!= '')
{
document.getElementById("cost").innerHTML = parseInt(limit) * parseInt(credit);
}
else
{
document.getElementById("cost").innerHTML = '';
}
}
</script>
</head>
<input type="number" value="0" min="0" class="form-control" placeholder="cost" id="credit" name="credit" onkeyup="calc();">
<input type="number" value="0" min="0" class="form-control" placeholder="quantity" id="limit" name="limit" onkeyup="calc();">
<p id="cost"></p>
Hope this will be useful
// get cost field
var _cost = document.getElementById("cost");
_cost.addEventListener('keyup',function(event){
updateCost()
})
// get quantity field
var _quantity = document.getElementById("quantity");
_quantity.addEventListener('keyup',function(event){
updateCost()
})
function updateCost(){
var _getCost = document.getElementById("cost").value;
var _getQuantity = document.getElementById("quantity").value;
var _total = _getCost*_getQuantity;
console.log(_total);
document.getElementById("updateValue").textContent = ""; // Erase previous value
document.getElementById("updateValue").textContent = _total // update with new value
}
jsfiddle
In case you consider using JQuery I've made this fiddle.
See if it works for you.
https://fiddle.jshell.net/9cpbdegt/
$(document).ready(function() {
$('#credit').keyup(function() {
recalc();
});
$('#limit').keyup(function() {
recalc();
});
function recalc() {
var credit = $("#credit").val();
var limit = $("#limit").val();
var result = credit * limit;
$("#result").text(result);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="form-control" placeholder="cost " id="credit" name="credit" value="0">x
<input type="text" class="form-control" placeholder="quantity" id="limit" name="limit" value="0">
<p id="result">0</p>
Try this:
<script >
function myFunction() {
document.getElementById('totalcost').innerHTML = document.getElementById('txt').value * document.getElementById('txt2').value;}
</script>
Also, change your HTML to this:
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="cost " id="txt" name="credit">
<input type="text" onkeypress="myFunction()" onkeyup="myFunction()" onclick="myFunction()" onmousemove="myFunction()" class="form-control" placeholder="quantity" id="txt2" name="limit">
Enter cost and quantity.
Note the change with the second input: id='txt' was changed to id='txt2'. This is because no 2 elements can have the same id.
Note: Untested.