I have a form in which a date/time picker is working fine.
I created JavaScript to calculate the two fields' date difference and show in a third field - named Course Duration.
Somehow I am not able to display the results in the "Course Duration" input Field.
Code:
function GetDays() {
var dropdt = new Date(document.getElementById("course_end_date").value);
var pickdt = new Date(document.getElementById("admission_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
if (document.getElementById("course_end_date")) {
document.getElementById("course_duration").value = GetDays();
}
}
<input id="admission_date" name="admission_date" placeholder="" type="text" class="form-control" value="" />
<input id="course_end_date" name="course_end_date" placeholder="" type="text" class="form-control" value="" />
<input id="course_duration" name="course_duration" placeholder="" type="text" class="form-control" value="" />
You need something to trigger the cal() function, which currently you don't have.
So I made a demo below which has a "Calculate" button. Enter your dates and then press the button, and it will run the calculation. As long as you enter valid dates, it should work.
For example, if you enter 2018-02-01 and 2018-02-02 it will return 366.
var calcButton = document.getElementById("calculate");
calcButton.addEventListener("click", cal);
function GetDays() {
var dropdt = new Date(document.getElementById("course_end_date").value);
var pickdt = new Date(document.getElementById("admission_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
if (document.getElementById("course_end_date")) {
document.getElementById("course_duration").value = GetDays();
}
}
<input id="admission_date" name="admission_date" placeholder="" type="text" class="form-control" value="" />
<input id="course_end_date" name="course_end_date" placeholder="" type="text" class="form-control" value="" />
<button id="calculate" type="button">Calculate</button>
<input id="course_duration" name="course_duration" placeholder="" type="text" class="form-control" value="" />
Related
I am using javascript calculation. multiply 2 numbers: number 1 * number 2 = total and how g-total but working only one value display?
I have need number 1 * number 2 = total and show Gtotal so please help and share a valuable idea...
HTML
<input
name="per_hour"
id="per_hour"
class="form-control"
value=""
onblur="perhour()"
placeholder="0"
/>
<input
name="per_hour_x"
id="per_hour_x"
class="form-control"
onblur="perhour()"
value=""
placeholder="0.00"
/>
Total
<input
name="per_hour_total"
id="per_hour_total"
class="form-control"
value=""
placeholder="0.00"
/>
G-Total
<input
type="text"
class="form-control total-fare"
id="total"
disabled
value="<?= $booking->total_fare ?>"
/>
<script>
function perhour() {
var per_hour = document.getElementById("per_hour").value;
var per_hour_x = document.getElementById("per_hour_x").value;
var amts = document.getElementById("total").value;
var totaperhour = Number(per_hour) * Number(per_hour_x);
var totalamt = Number(totaperhour) + Number(amts);
$("#per_hour_total").val(totaperhour).toFixed(2); //working
$("#total").val(totalamt).toFixed(2); //not working
}
</script>
It should be $('#per_hour_total').val(totaperhour.toFixed(2)); and not $('#per_hour_total').val(totaperhour).toFixed(2);
function perhour() {
var per_hour = document.getElementById("per_hour").value;
var per_hour_x = document.getElementById("per_hour_x").value;
var amts = document.getElementById("total").value;
var totaperhour = Number(per_hour) * Number(per_hour_x);
var totalamt = Number(totaperhour) + Number(amts);
$('#per_hour_total').val(totaperhour.toFixed(2));
$('#total').val(totalamt.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<div>
total
<input type="text" class="form-control total-fare" disabled id="total" value="">
</div>
<div>
per_hour
<input name="per_hour" id="per_hour" class="form-control" value="" onblur="perhour()" placeholder="0">
</div>
<div>
per_hour_x
<input name="per_hour_x" id="per_hour_x" class="form-control" onblur="perhour()" value="" placeholder="0.00">
</div>
<div>
per_hour_total
<input name="per_hour_total" id="per_hour_total" class="form-control" value="" placeholder="0.00">
</div>
the problem is the "total price" is not working.when i pick the "pickup date" and "drop date" it will show the value in the input form. i have to key in the number in "number of days" then the total price will calculate. i need the "total of price" is auto calculate. i have try various event of javascript. here i will attach my code. hope someone will help me. thanks in advance.
function sum() {
var txtFirstNumberValue = document.getElementById('num1').value;
var txtSecondNumberValue = document.getElementById('numdays2').value;
var result = parseInt(txtFirstNumberValue) * parseInt(txtSecondNumberValue);
if (!isNaN(result)) {
document.getElementById('num3').value = result;
}
}
function GetDays() {
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
if (document.getElementById("drop_date")) {
document.getElementById("numdays2").value = GetDays();
}
}
<label for="total">Price per day:</label>
<input type="text" name="price" id="num1" onkeyup="sum();" value="3" readonly>
<div id="pickup_date">
<p><label class="form">Pickup Date:</label>
<input type="date" class="textbox" id="pick_date" name="pickup_date" onchange="cal()" /></p>
</div>
<div id="dropoff_date">
<p><label class="form">Dropoff Date:</label>
<input type="date" class="textbox" id="drop_date" name="dropoff_date" onchange="cal()" /></p>
</div>
<div id="reserve_form">
<div id="numdays"><label class="form">Number of days:</label>
<input type="text" id="numdays2" name="numdays" oninput="sum();" />
<label for="total">Total Price (RM)</label>
<input type="text" name="test" placeholder="Total Price" value="" id="num3">
i expect that the total price can automatically calculate.
You just need to make sure your sum function (or in the example just cal) is being called when your inputs are complete and valid. Since you may want to restrict the user from manually setting the number of days I've demonstrated how you might do this by firing a change event programmatically. It's also current practice to attach events to elements programmatically instead of using the inline HTML5 event notation (e.g. "onchange=foo"), see Why are inline event handler attributes a bad idea in modern semantic HTML?
function setDate(event) {
var days = getDays();
// if the number of days is valid
if (!isNaN(days)) {
var nod = document.getElementById("numdays2");
nod.value = days;
// programmatically setting a value will not fire a change event
nod.dispatchEvent(new Event("change"));
}
}
function getDays() {
// returns NaN if either date does not hold a valid date
var dropdt = new Date(document.getElementById("drop_date").value);
var pickdt = new Date(document.getElementById("pick_date").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal() {
var pricePerDay = document.getElementById("pricePerDay").value;
if (0 == (pricePerDay = parseInt(pricePerDay))) { return } // TODO needs to handle decimal values
document.getElementById("total").value = parseInt(document.getElementById("numdays2").value) * pricePerDay;
}
function init() {
document.getElementById("drop_date").addEventListener("change", setDate);
document.getElementById("pick_date").addEventListener("change", setDate);
document.getElementById("numdays2").addEventListener("change", cal);
}
document.addEventListener("DOMContentLoaded", init);
<label for="total">Price per day:</label>
<input type="text" name="price" id="pricePerDay" value="" placeholder="Manually enter a value">
<div id="pickup_date">
<p><label class="form">Pickup Date:</label>
<input type="date" class="textbox" id="pick_date" name="pickup_date" /></p>
</div>
<div id="dropoff_date">
<p><label class="form">Dropoff Date:</label>
<input type="date" class="textbox" id="drop_date" name="dropoff_date" /></p>
</div>
<div id="reserve_form">
<div id="numdays"><label class="form">Number of days:</label>
<!-- numdays2 is readonly to ensure the date pickers are used -->
<input type="text" id="numdays2" name="numdays" readonly placeholder="Select dates above" />
<label for="total">Total Price (RM)</label>
<input id="total" type="text" readonly name="test" placeholder="Total Price" value="" id="num3">
</div>
</div>
Im new to Javascript and i was doing some DOM maniputalion, and i tried to create the BMI (body mass index) calculator, which is bodyMass / ( bodyWeight * bodyWeight ).
Then i've done some code:
HTML:
var bodyMass, bodyWeight;
bodyMass = parseInt(document.getElementById("bodyMass").value, 10);
bodyWeight = parseInt(document.getElementById("bodyWeight").value, 10);
var BMI = bodyMass / (bodyWeight * bodyWeight);
document.getElementById("check").onclick = function() {
alert(BMI);
}
<input type="text" placeholder="Body Mass" id="bodyMass">
<input type="text" placeholder="Body Weight" id="bodyWeight">
<button id="check">CHECK</button>
<div id="result"></div>
You need to calculate the body mass index when the button is clicked, not on page load. By not placing your code inside the event handler, you are calculating everything before any values are entered.
<input type="text" placeholder="Body Mass" id="bodyMass">
<input type="text" placeholder="Body Weight" id="bodyWeight">
<button id="check">CHECK</button>
<div id="result"></div>
<script>
var bodyMass, bodyWeight;
document.getElementById("check").onclick = function() {
bodyMass = parseInt(document.getElementById("bodyMass").value, 10);
bodyWeight = parseInt(document.getElementById("bodyWeight").value, 10);
var BMI = bodyMass / (bodyWeight * bodyWeight);
alert(BMI);
}
</script>
To make sure the value is not NaN before alerting, you use isNaN.
<input type="text" placeholder="Body Mass" id="bodyMass">
<input type="text" placeholder="Body Weight" id="bodyWeight">
<button id="check">CHECK</button>
<div id="result"></div>
<script>
var bodyMass, bodyWeight;
document.getElementById("check").onclick = function() {
bodyMass = parseInt(document.getElementById("bodyMass").value, 10);
bodyWeight = parseInt(document.getElementById("bodyWeight").value, 10);
var BMI = bodyMass / (bodyWeight * bodyWeight);
if(!isNaN(BMI)){
alert(BMI);
} else {
alert("Please enter two valid numbers!");
}
}
</script>
You are getting the values of bodyWeigt and bodyMass even before the button is clicked, at this stage (after parseInt-ing them) they are of course not a number (NaN).
Grab the values on click of the button i.e when the user has (hopefully) entered some valid values...
document.getElementById("check").onclick = function() {
var bodyMass, bodyWeight;
bodyMass = parseInt(document.getElementById("bodyMass").value);
bodyWeight = parseInt(document.getElementById("bodyWeight").value);
var BMI = bodyMass / (bodyWeight * bodyWeight);
alert(BMI);
}
<input type="number" placeholder="Body Mass" id="bodyMass">
<input type="number" placeholder="Body Weight" id="bodyWeight">
<button id="check">CHECK</button>
<div id="result"></div>
Because your input are numeric, you should instead do
<input type="number" placeholder="Body Mass" id="bodyMass">
<input type="number" placeholder="Body Weight" id="bodyWeight">
and place the calculation inside the button click event, else the calculation will get executed once the page loads and you will get a NaN alert.
I am developing a task management system in that i am having the age field in registration form i am having doubt about how to update the field automatically when i click.
my script is
<script>
var a = document.age1.dob.value;
age = a.getFullYear();
var curr = new Date();
year = curr.getFullYear();
var age1 = year - age;
</script>
i calculated the age and stored it in age1 variable.
<form id="form2" action="#" method="post" name="age1">
<h4><b>Register here</b></h4>
<b>Name</b>: <input type="text" name="name" required="required" placeholder="Your name" pattern="[a-zA-Z0-9\s]+"><br><br>
<b>E-mail</b>: <input type="email" name="email" required="required" placeholder="someone#example.com" pattern="[a-z0-9._+%-]+#[a-z0-9.-]+\.[a-z]{2,4}$"><br><br>
<b>Password</b>: <input type="password" name="password" required="required"><br><br>
<b>DOB</b>: <input type="text" name="dob" required placeholder="dd/mm/yyyy" pattern="^[0-3]?[0-9].[0-3]?[0-9].(?:[0-9]{2})?[0-9]{2}$"><br><br>
<b>Age</b>: <input type="text" name="age" id="age2"><br><br>
<b>Address</b>: <textarea name="address" rows="6" cols="30"></textarea>
<button id="butr" type="submit" class="btn btn-warning">Signup</button>
After i input my DOB in the registration form and click the age field i want the calculated age that i stored it in age1 variable to automatically update the value in age field that i have it in my registration form
Add an onchange function to dob field
<input type="text" onchange="ageCalculation()" name="dob">
Add this code in your <script>
function ageCalculation(){
if(document.age1.dob.value!==""){
var a = document.age1.dob.value;
a=new Date(a);
age = a.getFullYear();
var curr = new Date();
year = curr.getFullYear();
var age1 = year - age;
document.age1.age.value=age1;
}
}
I want to display total day in text box automatically if I choose from two dates, but I can not get it. If I don't use Javascript, it works. Datepicker can't work if haven't used Javascript. How can I do that?
This is my script:
<input class="form-control" onchange="cal()" placeholder="Choose Date " type="text" id="example1" name="startdate" required="required" "/>
<input class="form-control" onchange="cal()" placeholder="Choose Date " type="text" id="example2" name="enddate" required="required" disabled="disabled" "/>
<input class="form-control" type="text" id="numdays2" name="total_leave"/>
This is java script:
<!--calendar Java script -->
<script type="text/javascript">
$(document).ready(function () {
$('#example1').datePicker({
format: "yyyy-mm-dd"
});
});
</script>
<!-- Datepicker -->
<script type="text/javascript">
$(document).ready(function () {
$('#example2').datePicker({
format: "yyyy-mm-dd"
});
});
</script>
<!-- calculate leave total day -->
<script type="text/javascript">
function GetDays(){
var dropdt = new Date(document.getElementById("example2").value);
var pickdt = new Date(document.getElementById("example1").value);
return parseInt((dropdt -(pickdt)) / (24 * 3600 * 1000))+1|| parseInt(1);
}
function cal(){
if(document.getElementById("example1")){
document.getElementById("numdays2").value=GetDays();
}
}
</script>
There are quite a few bits in your code that need changing / fixing, so here is a working example based on your original code.
<input class="form-control" placeholder="Choose Date " type="text" id="example1" name="startdate" required="required" />
<input class="form-control" placeholder="Choose Date " type="text" id="example2" name="enddate" required="required" />
<input class="form-control" type="text" id="numdays2" name="total_leave"/>
$(document).ready(function(){
$('#example1').datepicker({
format: "yyyy-mm-dd",
onSelect: function(){
cal()
}
});
$('#example2').datepicker({
format: "yyyy-mm-dd",
onSelect: function(){
cal()
}
});
});
function GetDays(){
var dropdt = new Date(document.getElementById("example2").value);
var pickdt = new Date(document.getElementById("example1").value);
return parseInt((dropdt -(pickdt)) / (24 * 3600 * 1000))+1|| parseInt(1);
}
function cal(){
if(document.getElementById("example1")){
document.getElementById("numdays2").value=GetDays();
}
}
Working Demo
changeDate event is triggered every time the date is selected or changed
DatePicker(Events)
HTML
<input placeholder="Start Date " type="text" id="StartDate" />
<input placeholder="End Date " type="text" id="EndDate" />
<input type="text" id="datediff" />
JS
$('#StartDate,#EndDate').datepicker({
format: "yyyy-mm-dd",
autoclose: true,
});
$('#StartDate,#EndDate').datepicker().on('changeDate', function () {
if ($('#StartDate').val() != '' && $('#EndDate').val() != '') {
var date1 = new Date($('#StartDate').val());
var date2 = new Date($('#EndDate').val());
var timeDiff = date2.getTime() - date1.getTime();
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24));
$('#datediff').val(diffDays);
}
})