how can i do dynamic form calculation without submit? submitting is about php server. I need to calculate this form with limiting max values. Example result value can't be above buy value. when above must give error submit button disabled.
I can't find any solution.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
$("#storage","#result","#account").on(keyup, change(function(){
var abc = $("#abc").val();
var price = $("#price").val();
var storage = $("#capacity").val() - $("#abc").val();
$("#storage").val(storage);
var result = $("#price").val() * $("#abc").val();
$("#result").val(result);
var account = buy - result;
$("#account").val(account);
});
});
</script>
</head>
<body>
<form method="post" action="" >
<input id="buy" type="hidden" class="form-control" name="buy" value="5000000" />
<input type="hidden" id="capacity" class="form-control" name="capacity" value="1000000" />
Storage : <input id="storage" type="text" class="form-control" name="storage" min="0" max="1000000" value=""/><br>
Abc: <input id="abc" type="text" class="form-control" name="abc" min="0" max="1000000" value="" /> <br>
Price: <input id="price" type="text" class="form-control" name="price" value="15" /> <br>
Result: <input id="result" type="text" class="form-control" name="result" value=""/> <br>
Account: <input id="account" type="text" class="form-control" name="account" max="5000000" value="" /> <br>
<input type="button" id="submit" value="submit">
</form>
</body>
</html>
Use an input / keyup event listener. For example (Vanilla JS):
document.getElementById('myInput').addEventListener("keyup", function() {
console.log(document.getElementById("myInput").value);
// Do your stuff here
});
<input id="myInput" />
Or with jQuery:
$('#myInput').keyup(function() {
console.log($("#myInput").val());
// Do your stuff here
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="myInput" />
Although this is heplful, JavaScript (besides Node) is client-side and can be easily overriden, so make sure you evaluate the input in the backend too.
Related
I am using a simple calculator form and i am trying to use javascript to calculate the total. I have referenced the source and ID's correct, however i will upload.
When clicking the calculate button the page refreshes the values back to normal.
see below for HTML and JS
function calculate() {
'use strict';
var total;
var quantity = document.getElementsById('quantity').value;
var unitPrice = document.getElementById('price').value;
var theVat = document.getElementById('vat').value;
var theDiscount = document.getElementById('discount').value;
total = quantity * unitPrice;
total = total + (total * theVat / 100) - (total * theDiscount / 100);
total = total.toFixed(2);
document.getElementById('total').value = "£" + total;
return false;
}
function initCal() {
'use strict';
document.getElementById('theCalculatorForm').onsubmit = calculate;
}
window.onload = initCal;
<!doctype html>
<html class="no-js" lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Innovative Multimedia - Simple Calculator</title>
<link rel="stylesheet" href="css/foundation.min.css">
<link rel="stylesheet" href="css/app.css">
</head>
<body>
<div class="container">
<div class="row columns text-center">
<h2>Innovative Multimedia - Introduction to JavaScript</h2>
<p> In this application the user will enter the required details and the application will calculate the total cost.</p>
</div>
<div class="row">
<h3> Simple Calculator</h3>
<form action="" method="post" id="theCalculatorForm">
<fieldset>
<p>Use this form to calculate the order total.</p>
<div><label for="quantity">Quantity</label><input type="number" name="quantity" id="quantity" value="1" min="1" required></div>
<div><label for="price">Price Per Unit</label><input type="number" name="price" id="price" value="1.00" required></div>
<div><label for="vat">VAT (%)</label><input type="number" name="vat" id="vat" value="17" required disabled></div>
<div><label for="discount">Discount (%)</label><input type="number" name="discount" id="discount" value="10" required disabled></div>
<div><label for="total">Total</label><input type="text" name="total" id="total" value="0" required disabled></div>
<div><input type="submit" value="Calculate" id="submitCal"></div>
</fieldset>
</form>
</div>
</div>
<script src="js/calculator.js"></script>
<script src="js/jquery.js"></script>
<script src="js/what-input.js"></script>
<script src="js/foundation.js"></script>
<script src="js/app.js"></script>
</body>
</html>
If you need anything please ask.
<form> we use it to send data by two methods (post/get) so when you click
in Button calculate all values sends and page refreshed
use div for exemple to not refresh the web page
replace the form tag with div
like this
<div id="theCalculatorForm">
</div>
<!---- Your code after will be like this ------>
<div id="theCalculatorForm">
<fieldset>
<p>Use this form to calculate the order total.</p>
<div><label for="quantity">Quantity</label><input type="number" name="quantity" id="quantity" value="1" min="1" required></div>
<div><label for="price">Price Per Unit</label><input type="number" name="price" id="price" value="1.00" required></div>
<div><label for="vat">VAT (%)</label><input type="number" name="vat" id="vat" value="17" required disabled></div>
<div><label for="discount">Discount (%)</label><input type="number" name="discount" id="discount" value="10" required disabled></div>
<div><label for="total">Total</label><input type="text" name="total" id="total" value="0" required disabled></div>
<div><input type="submit" value="Calculate" id="submitCal"></div>
</fieldset>
</div>
In your calculate function, take one event parameter and prevent the default action from occurring:
function calculate(event) {
event.preventDefault();
//other code will work
}
Then use an event in your call:
<button onclick="calculate(e)">Calculate</button>
And it will work
I have the following code, and I want the gather_form_elements array to show up as an unordered list.
Here is my html part:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta author="Justin Roohparvar">
<link rel="stylesheet" href="CSS\css.css">
<script src="Javascript/form.js"></script>
<title>Contact Form</title>
</head>
<body>
<form method="POST" action="week_1_contact_form.html">
<h1>Contact Form</h1>
<input id="first_name" type="text" maxlength="50" size ="25" placeholder="First Name" required> <br /><br />
<input id="last_name" type="text" maxlength="50" size="25" placeholder="Last Name" required> <br /><br />
<input id = "email" type="email" name="email" placeholder="Email" required> <br /> <br />
<input id="phone_number" type="tel" name="phone_number" placeholder="Phone Number" required><br /><br />
<input type="Submit" name="Submit" value="Submit" onclick="getFormElements()">
</form>
</body>
</html>
And my form.js code is below:
function getFormElements() {
var gather_form_elements = new Array(document.getElementById("first_name"), document.getElementById("last_name"),
document.getElementById("email"), document.getElementById("phone_number"));
displayValues(gather_form_elements);
}
function displayValues(gather_form_elements) {
for(i=0; i<gather_form_elements.length; i++)
{
document.write(gather_form_elements[i]);
}
}
Any suggestions would be appreciated.
First of all, you have to get values from your inputs, not just elements itself. With your approach, it should look like this:
function getFormElements() {
var gather_form_elements = new Array(document.getElementById("first_name").value, document.getElementById("last_name").value,
document.getElementById("email").value, document.getElementById("phone_number").value);
displayValues(gather_form_elements);
}
function displayValues(gather_form_elements) {
document.write('<ul>');
for(i=0; i<gather_form_elements.length; i++)
{
document.write('<li>'+gather_form_elements[i]+'</li>');
}
document.write('</ul>');
}
As Newbie says, you need to get the value of each controls. A much simpler version of the listener is to make use of the form's elements collection. Controls must have a name to be successful, you can leverage that to work out which controls to get the values of:
function getFormElements(form) {
var values = [];
[].forEach.call(form.elements, function(control) {
if (control.name) {
values.push(control.value);
}
});
// Show values for testing
console.log(values);
return values;
}
<form onsubmit="getFormElements(this); return false"> <!-- prevent submit for testing -->
<h1>Contact Form</h1>
<input name="first_name" type="text" maxlength="50" size="25" placeholder="First Name" required> <br><br>
<input name="last_name" type="text" maxlength="50" size="25" placeholder="Last Name" required> <br><br>
<input name="email" type="email" placeholder="Email" required> <br> <br>
<input name="phone_number" type="tel" placeholder="Phone Number" required><br><br>
<input type="submit" value="Submit">
</form>
This lets you add more controls and doesn't care what you call them.
So only name controls that need a name, don't use IDs if you don't need them and put the submit listener on the form's submit handler so that no matter how the form is submitted, the listener is called. ;-)
I am trying to design a form. which takes input and after clicking on calculate gives output.
text field 'State' accepts only 2 uppercase letters
I am stuck in creating Calculate button.
The calculate button needs to determine the number of miles traveled by the customer and the total charge due from the customer.
below is my form:
function ValidateData() {
var InputText = document.getElementById('state').value;
var Expression = /^[zA-Z]*$/
if (InputText.search(Expression) == -1) {
alert("Must contain only A-Z");
return false;
}
}
body {
background-color: powderblue;
}
.upper {
text-transform: uppercase;
}
<!DOCTYPE html>
<html>
<head><b>Calculate Rental Charges</b></head><br>
<body>
<form action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="">
<br> Address:
<br>
<input type="text" name="address" value="">
<br> city:
<br>
<input type="text" name="city" value="">
<br> State:
<br>
<input type="text" id="state" name="State" cssclass="upper" value="">
<br> Zip code:<br>
<input type="text" name="zipcode" value="">
<br> Beginning odometer reading(in miles):<br>
<input type="text" name="zipcode" value="">
<br> Ending odometer reading(in miles):<br>
<input type="text" name="zipcode" value="" maxlength="10">
<br>
<br>
<input type="submit" value="Submit" OnClientClick="return ValidateData()">
</form>
I have designed one script which validates that state should have only upper case letters.
I want to calculate no. of miles driven which can be done by getting difference of starting miles and ending miles.
For calculating the total charge due from the customer.:
i have to use a constant for the $15 per day charge and the $0.12 mileage rate.
IS there any way to get all this result on single click of submit button.
I created 2 input fields, one to store the total distance and other one is to store the cost. Both are disabled.
Add a button to calculate.
Then add a function like this and call it on button click.
function calc(){
var totalMile = parseInt(document.getElementsByName("endMile")[0].value)-parseInt(document.getElementsByName("startMile")[0].value)
document.getElementById("result").value=totalMile;
var cost=(totalMile*0.12)+15
document.getElementById("cost").value='$'+cost;
}
function ValidateData() {
var InputText = document.getElementById('state').value;
var Expression = /^[A-Z]*$/
if (InputText.search(Expression) == -1) {
alert("Must contain only A-Z");
return false;
}
}
function calc(){
var totalMile = parseInt(document.getElementsByName("endMile")[0].value)-parseInt(document.getElementsByName("startMile")[0].value)
document.getElementById("result").value=totalMile;
var cost=(totalMile*0.12)+15
document.getElementById("cost").value='$'+cost;
}
body {
background-color: powderblue;
}
.upper {
text-transform: uppercase;
}
<!DOCTYPE html>
<html>
<head><b>Calculate Rental Charges</b></head><br>
<body>
<form method="post" action="/action_page.php">
First name:<br>
<input type="text" name="firstname" value="">
<br> Address:
<br>
<input type="text" name="address" value="">
<br> city:
<br>
<input type="text" name="city" value="">
<br> State:
<br>
<input type="text" id="state" name="State" cssclass="upper" value="">
<br> Zip code:<br>
<input type="text" name="zipcode" value="">
<br> Beginning odometer reading(in miles):<br>
<input type="text" name="startMile" value="">
<br> Ending odometer reading(in miles):<br>
<input type="text" name="endMile" value="" maxlength="10">
<br>
<button type="button" onclick="calc();">Calc</button>
<br />
Total Miles : <br />
<input disabled id="result" />
<br />
Total Cost <br />
<input disabled id="cost" />
<br />
<br>
<input type="submit" value="Submit" Onclick="return ValidateData();">
</form>
I am having trouble writing to the console with the following code. Unsure as to why it is not working as am a beginner JavaScript programmer. May be a stupid question because I am new to JavaScript.
Javascript:
function process(){
'use strict';
var user = document.getElementById("user").value;
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
var pass = document.getElementById("pass").value;
var age = document.getElementById("age").value;
console.log(user);
};
function init(){
'use strict';
document.getElementById('signUp').onsubmit = process;
};
window.onload = init;
html:
<!doctype html>
<html>
<head>
<meta charset="UTF-8" />
<title>Employee Register</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen"/>
</head>
<body>
<form action="#" method="post" id="signUp" class="form">
<h1>Sign up.
<span>Please complete all information.</span>
</h1>
<label for="user">
<span>Username:</span>
<input type="text" name="user" id="user" required>
</label>
<label for="name">
<span>Full Name:</span>
<input type="text" name="name" id="name" required>
</label>
<label for="email">
<span>Email Address:</span>
<input type="email" name="email" id="email" required>
</label>
<label for="pass">
<span>Password:</span>
<input type="password" name="pass" id="pass" required>
</label>
<label for="age">
<span>Age:</span>
<input type="text" name="age" id="age" required>
</label>
<input type="submit" value="Submit" id="submit">
</form>
<div id="members" class="output">
<h1>Registered Members</h1>
</div>
<script src="register.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
The reason for this is that the log is renewed for every request (in case of Chrome browser) and as you are setting the console.log to be fired onsubmit the log is logged but will be cleared immediately
Check the checkbox Preserve Log in the console of Chrome.
You can change the input type to a normal button to prevent the submit <input type="button" value="Submit" id="submit">.
After doing whatever you want with the fields you can submit the form with signUp.submit() or document.getElementById('signUp').submit().
I am kind of new to JQuery and Javascript and need your help on what I am missing here. I know the code works in jsfiddle.net but when I actually run it on my computer it's not doing anything. I want to keep the Object Oriented functions in "updated-formcheck.js" file separately.
I have a form validation HTML file with a jQuery function that calls my "updated-formcheck.js" file that checks all the empty fields and returns a msg. But when a submit button is clicked, nothing happens. Can you tell me why?
HTML file:
<script src="updated-formcheck.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<form id="myform" method="post" action="#">
<fieldset>
<label for="attendee">I am a...<font color="red">*</font>:<br />
<br />
</label>
<select id="attendee" name="attendee" >
<option value="">-- Please Choose --</option>
<option value="RETURNING" >Returning Attendee</option>
<option value="FIRST_TIME" >First Time Attendee</option>
</select>
<label for="fullName"><br />
<br />
Full Name<font color="red">*</font>:</label>
<p><input type="text" id="fullName" name="fullName" value="" />
</p>
<p> </p>
<label for="address1">Street Address<font color="red">*</font>:</label>
<p>
<input type="text" id="address1" name="address1" value=""/>
</p>
<p>
<input type="text" id="address2" name="address2" value="" />
</p>
<label for="city"><br />
City<font color="red">*</font>:</label>
<p>
<input type="text" id="city" name="city" value="" />
</p>
<label for="stateProvince"><br />
State/County/Province:</label>
<p>
<input type="text" id="stateProvince" name="stateProvince" value="" />
</p>
<label for="zipPostalCode">ZIP/Postal Code:<br />
</label>
<p>
<input type="text" id="zipPostalCode" name="zipPostalCode" value="" />
</p>
<input type="hidden" name="submitted" value="true" />
<input type="submit" value="Submit" id="btnSubmit"/>
</fieldset>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#btnSubmit').click(function(e) {
validateNow(e);
});
});
</script>
In "updated-formcheck.js" file:
function validateNow(eventObj){
var isValid = true;
$('input[type="text"].required, textarea.required, select.required').each(function() {
if ($.trim($(this).val()) == '') {
isValid = false;
$(this).css({
"border": "1px solid red",
"background": "#FFCECE"
});
}
else {
$(this).css({
"border": "",
"background": ""
});
}
});
if (isValid == false) {
eventObj.preventDefault();
alert(this.e);
}else
this.s;
}
Because
$('input[type="text"].required, textarea.required, select.required')
in your code currently return an empty array, so each function is not called.
This is because you are looking for dom elements with a css class "required" that you doesn't have.
To get your code working I added a "required" class, which your js code is looking for, on the city element. I also updated the jQuery bind event to the form submit instead of a button click.
<html>
<head>
</head>
<body>
<form id="myform" method="post" action="#">
<fieldset>
<label for="attendee">I am a...<font color="red">*</font>:<br />
<br />
</label>
<select id="attendee" name="attendee" >
<option value="">-- Please Choose --</option>
<option value="RETURNING" >Returning Attendee</option>
<option value="FIRST_TIME" >First Time Attendee</option>
</select>
<label for="fullName"><br />
<br />
Full Name<font color="red">*</font>:</label>
<p><input type="text" id="fullName" name="fullName" value="" />
</p>
<p> </p>
<label for="address1">Street Address<font color="red">*</font>:</label>
<p>
<input type="text" id="address1" name="address1" value=""/>
</p>
<p>
<input type="text" id="address2" name="address2" value="" />
</p>
<label for="city"><br />
City<font color="red">*</font>:</label>
<p>
<input type="text" id="city" name="city" value="" class="required" />
</p>
<label for="stateProvince"><br />
State/County/Province:</label>
<p>
<input type="text" id="stateProvince" name="stateProvince" value="" />
</p>
<label for="zipPostalCode">ZIP/Postal Code:<br />
</label>
<p>
<input type="text" id="zipPostalCode" name="zipPostalCode" value="" />
</p>
<input type="hidden" name="submitted" value="true" />
<input type="submit" value="Submit" id="btnSubmit"/>
</fieldset>
</form>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="updated-formcheck.js" ></script>
<script type="text/javascript">
$(document).ready(function() {
$('#myform').on('submit', function(e) {
//e.preventDefault();
validateNow(e);
return false;
});
});
</script>
</body>
</html>