This question already has answers here:
How to calculate number of days between two dates?
(42 answers)
Closed 4 years ago.
I am facing one problem. I am unable to differentiate the date difference using the javascript. I am explaining my code below.
var startdate_val = document.getElementById("stdate").value;
var enddate_val = document.getElementById("enddate").value;
var one_day=1000*60*60*24;
var x=startdate_val.split("-");
var y=enddate_val.split("-");
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0])
var month1=x[1]-1;
var month2=y[1]-1;
var date_diff = Math.ceil((date2.getTime()-date1.getTime())/(one_day));
console.log('date',date_diff <= 0);
Here I need enddate always should be greater than the start date. Here I am attaching my datetime code.
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">Start Date</label>
<input id="stdate" type="text" class="form-control datetime" value="" placeholder="17-06-2017"/>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">End Date</label>
<input id="enddate" type="text" class="form-control datetime" value="" placeholder="17-06-2017"/>
</div>
</div>
</div>
Here I am getting the date field value like this i.e-03-01-2018 02:46. I need always the end date time should be greater than the start date time but in my case in console message always I am getting the result false.
Try this:
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">Start Date</label>
<input id="stdate" type="text" class="form-control datetime" value="17-06-2017" placeholder="17-06-2017"/>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">End Date</label>
<input id="enddate" type="text" class="form-control datetime" value="17-07-2017" placeholder="17-06-2017"/>
</div>
</div>
</div>
var startdate_val = document.getElementById("stdate").value;
var enddate_val = document.getElementById("enddate").value;
var one_day=1000*60*60*24;
var x=startdate_val.split("-");
var y=enddate_val.split("-");
var date1=new Date(x[2],(x[1]-1),x[0]);
var date2=new Date(y[2],(y[1]-1),y[0])
var month1=x[1]-1;
var month2=y[1]-1;
var date_diff = Math.ceil((date2.getTime()-date1.getTime())/(one_day));
console.log(date_diff >= 0);
You just need to change the line: console.log('date',date_diff <= 0);
Simply do like this :
var startdate_val = document.getElementById("stdate").value;
var enddate_val = document.getElementById("enddate").value;
var stdate = new Date(startdate_val).toISOString();
var enddate = new Date(enddate_val).toISOString();
//Then
Console.log(enddate >= stdate);
Sample Code that I've tried:
var startdate_val = '01-03-2018 02:45';
var enddate_val = '01-03-2018 02:45';
var stdate = new Date(startdate_val);
var enddate = new Date(enddate_val);
//Then
alert(enddate >= stdate);
Returns True
Fiddle
Converting the string to Date Object will be better than the manual labor.
in your HTML code, there is no value so you can't compare it to page load time, because it is blank.
somehow if you are using any click functionality then
please update your code below.
var startdate_val = document.getElementById("stdate").value;
var enddate_val = document.getElementById("enddate").value;
var one_day = 1000 * 60 * 60 * 24;
var x = startdate_val.split("-");
var y = enddate_val.split("-");
var date1 = new Date(x[2], (x[1] - 1), x[0]);
var date2 = new Date(y[2], (y[1] - 1), y[0])
var month1 = x[1] - 1;
var month2 = y[1] - 1;
var date_diff = Math.ceil((date2.getTime() - date1.getTime()) / (one_day));
if (date_diff <= 0)
console.log(false);
else
console.log(true);
AND HTML FOR PAGE LOAD
<div class="row">
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">Start Date</label>
<input id="stdate" type="text" class="form-control datetime" value="17-06-2017" placeholder="17-06-2017" />
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-6">
<div class="pad-bot-10">
<label for="raised">End Date</label>
<input id="enddate" type="text" class="form-control datetime" value="18-06-2017" placeholder="17-06-2017" />
</div>
</div>
</div>
Related
Currently, I have 4 digit numbers showing randomly if I refresh the page. I tryna add the years infront of the 4 digit numbers but only 4 digit numbers still showing. Is there anyway to show the years in front of random numbers? (Example, 20221234).
<label class="control-label col-sm-4" for="refno">REF nos :</label>
<div class="col-sm-4">
<script type="text/javascript">
now = new Date();
randomNum = '';
randomNum += Math.round(Math.random() * 9);
randomNum += Math.round(Math.random() * 9);
randomNum += now.getTime().toString().slice(-2);
window.onload = function () {
document.getElementById("refno").value = randomNum;
}
document.getElementById("refno").innerHTML = new Date().getFullYear();
</script>
<p class="form-control-static" style="margin-top: -6px;">
<input type="text" class="form-control" id="refno" name="refno" value="<?php echo $refno; ?>" disabled>
</p>
</div>
<div class="col-sm-10"></div>
You can't use innerHTML on an input tag.
You can use document.getElementById('someID').value to replace the value.
const now = new Date();
let randomNum = '';
randomNum += Math.round(Math.random() * 9);
randomNum += Math.round(Math.random() * 9);
randomNum += now.getTime().toString().slice(-2);
document.getElementById("refno").value = `${new Date().getFullYear()}${randomNum}`;
<label class="control-label col-sm-4" for="refno">REF nos :</label>
<div class="col-sm-4">
<br/>
<p class="form-control-static" style="margin-top: -6px;">
<input type="text" class="form-control" id="refno" name="refno" value="" disabled />
</p>
</div>
<div class="col-sm-10"></div>
I'm trying to send the value of GST to order.js file if and only if the value of VAT mode is selected to be "with Vat" form the page new_order.php
<div class="form-group row">
<label for="vat" class="col-sm-3 col-form-label" onChange="getVatMode(this.value);" align="right">VAT Mode</label>
<div class="col-sm-6">
<select name="vatMode" value="data" class="form-control" id="vatMode" required="required">
<option value="1">Without VAT</option>
<option value="2">With VAT</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="gst" class="col-sm-3 col-form-label" align="right">GST (13%)</label>
<div class="col-sm-6">
<input type="text" readonly name="gst" class="form-control form-control-sm" id="gst" required/>
</div>
</div>
and I need to pass this value of VAT to be passed to order.js page without loading for calculation of sum
function calculate(dis,paid){
var sub_total = 0;
var gst = 0;
var net_total = 0;
var discount = dis;
var paid_amt = paid;
var due = 0;
$(".amt").each(function(){
sub_total = sub_total + ($(this).html() * 1);
})
gst = Math.round(0.13 * sub_total);
net_total = gst + sub_total;
net_total = net_total - discount;
due = net_total - paid_amt;
$("#gst").val(gst);
$("#sub_total").val(sub_total);
$("#discount").val(discount);
$("#net_total").val(net_total);
//$("#paid")
$("#due").val(due);
With Jquery you can use $("#YourFormId").serialize():
$("form").on( "submit", function( event ) {
event.preventDefault();
console.log($(this).serialize());
});
For a form element's value to be included in the serialized string, the element must have a name attribute
https://api.jquery.com/serialize/
I'm trying to calculate the date of birth from a given age.
My logic is
When we enter an age say '5'. The date of birth will be calculated as exactly 5 years from the current date. Example current date is 20/8/2018.
Then date of birth will be 20/8/2013 if the age is 5.
So below is my code:
function validatedob() {
var dob_value = document.getElementById('dob').value;
var age_value = document.getElementById('age').value;
var current_date = new Date();
var birth_date = new Date();
var birth_year = current_date.getFullYear() - age_value;
var birth_month = current_date.getMonth();
var birth_day = current_date.getDate();
birth_date.setDate(current_date.getFullYear() - age_value);
birth_date.setMonth(current_date.getMonth());
birth_date.setFullYear(current_date.getDate());
document.getElementById('dob').setDate(birth_day);
document.getElementById('dob').setMonth(birth_month);
document.getElementById('dob').setFullYear(birth_year);
}
<div class="form-inline" id="Age">
<label for="age">Age</label>
<input id="age" type="integer" name="age" onchange="validatedob()">
</div>
<div class="form-inline" id="birth">
<label for="DOB">Date of Birth</label>
<input id="dob" type="date" value="Unknown" name="date_of_birth" max="31-12-2030">
</div>
This is not working. I'm not goodwith html properties.
Can someone help me? how to achieve this?
Here is the simple answer:
> d1 = new Date(2018, 00, 01)
Date 2018-01-01T00:00:00.000Z
> d2 = new Date(d1.getFullYear() - 5, d1.getMonth(), d1.getDate())
Date 2013-01-01T00:00:00.000Z
But, I would suggest to use a library such as Luxon.
Date manipulation is an absolute nightmare if you do it by yourself. This video from Computerphile summarizes it better than I could:
https://www.youtube.com/watch?v=-5wpm-gesOY
Here is a really simple solution that works and some changes to your HTML.
Changes to HTML:
The div and label both had the id "age", this must be unique.
type="integer"doesn't exist, so i changed it to type="number".
And value="unknown"isn't the right format "yyy-MM-dd", so i just removed it.
for="DOB"to for="dob", now that works aswell
Code:
HTML
<div class="form-inline">
<label for="age">Age</label>
<input id="age" type="number" name="age"onchange="validatedob()">
</div>
<div class="form-inline" id="birth">
<label for="dob">Date of Birth</label>
<input id="dob" type="date" name="date_of_birth" max="31-12-2030">
</div>
JavaScript
function validatedob() {
var age_value = document.getElementById("age").value;
var current_date = new Date();
var birth_date = new Date(current_date.getFullYear() - age_value, current_date.getMonth(), current_date.getDate() + 1);
document.getElementById("dob").valueAsDate = birth_date;
}
Here is some sample code for your reference
https://codepen.io/ji_in_coding/pen/wEvoMK
<div class="form-inline" id="Age">
<label for="age">Age</label>
<input id="age" type="integer" name="age" onchange="validatedob()">
</div>
<div class="form-inline" id="birth" >
<label for="DOB">Date of Birth</label>
<input id="dob" type="input" name="date_of_birth">
</div>
Javascript
function validatedob()
{
var age_value = document.getElementById("age").value;
var today = new Date();
var calculated_birthday = new Date(
parseInt(today.getFullYear())+parseInt(age_value),
today.getMonth(),
today.getDate());
document.getElementById("dob").value = calculated_birthday.toLocaleDateString("en-US");
}
You're issue is that you are trying to setDate and cie on a HTMLElement. The input dob expect a string formatted as yyyy-MM-dd. You can try something like that:
var $dob = document.getElementById('dob');
var $age = document.getElementById('age');
function validatedob() {
var age = $age.value;
var date = new Date();
date.setFullYear(date.getFullYear() - age);
$dob.value = formatDate(date);
}
function formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
return [year, month, day].join('-');
}
<div class="form-inline" id="Age">
<label for="age">Age</label>
<input id="age" type="integer" name="age" onchange="validatedob()">
</div>
<div class="form-inline" id="birth">
<label for="DOB">Date of Birth</label>
<input id="dob" type="date" value="Unknown" name="date_of_birth" max="31-12-2030">
</div>
PS: For performance purpose avoid to repeat document.getElementById(...) in each method call. Do it once as done in my example.
I've created cash denomination calculator in jquery, and it's working fine once you add entry but suppose if you try to change those entries then it's not calculating values as i expected.
Just fill those values and you'll get total of all, but if try to change the value of input box inside div with '.mul_by' class[i.e. the small input box before '=' sign] then it's not calculating the total properly.
And here's the jsFiddle for the same.
$('.mul_by').each(function (i) {
var _this = $(this),
//set default input value to zero inside .mul-by div
setZero = _this.find('.form-control').val(0),
//set default input value to zero inside .mul-val div
setDenominationVal = _this.siblings('.mul_val').find('.form-control').val(0),
//set default input value to zero inside .total div
setTotalVal = $('.total').val(0);
setZero.on('change', function () {
//watch and store input val. inside .mul_by
var getUpdatedVal = _this.find('.form-control').val(),
//get label text
getDenominationVal = parseInt(_this.siblings('label').text()),
//update mul_by div after multiplication
updateDenominationVal = _this.siblings('.mul_val').find('.form-control');
if (getUpdatedVal > 0) {
var vals = updateDenominationVal.val(getUpdatedVal * getDenominationVal);
total = parseInt(setTotalVal.val()) + parseInt(vals.val());
setTotalVal.val(total);
} else {
updateDenominationVal.val(0);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-2 col-xs-2" for="batch">2000</label>
<div class="col-md-1 col-xs-4 mul_by">
<span>x </span> <input type="text" class="form-control">
</div>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2 col-xs-2" for="batch">500</label>
<div class="col-md-1 col-xs-4 mul_by">
<span>x </span> <input type="text" class="form-control">
</div>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2 col-xs-2" for="batch">100</label>
<div class="col-md-1 col-xs-4 mul_by">
<span>x </span> <input type="text" class="form-control">
</div>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<hr>
<label class="control-label col-md-2 col-xs-2" for="batch">total:</label>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control total">
</div>
</div>
</form>
How do i update total after making changes?
Hope you understand it. Thanks in advance for your help.
Please check this code i get proper result I had made lot of changes at end hope you will get desired result:-
$(document).ready(function () {
$('.mul_by').each(function (i) {
var _this = $(this),
//set default input value to zero inside .mul-by div
setZero = _this.find('.form-control').val(0),
//set default input value to zero inside .mul-val div
setDenominationVal = _this.siblings('.mul_val').find('.form-control').val(0);
//set default input value to zero inside .total div
setTotalVal = $('.total').val(0);
setZero.on('change', function () {
var getcurrentval = $(this).val();
console.log('getcurrentval',getcurrentval)
//watch and store input val. inside .mul_by
var getUpdatedVal = _this.find('.form-control').val(),
//get label text
getDenominationVal = parseInt(_this.siblings('label').text()),
//update mul_by div after multiplication
updateDenominationVal = _this.siblings('.mul_val').find('.form-control');
console.log(getUpdatedVal,getDenominationVal)
var vals = 0,total=0;
if(getUpdatedVal > 0){
if(updateDenominationVal.val()>0){
vals = updateDenominationVal.val(getUpdatedVal * getDenominationVal - updateDenominationVal.val());
total = parseInt(setTotalVal.val()) + parseInt(vals.val()) ;
updateDenominationVal.val(getUpdatedVal * getDenominationVal);
console.log('total',total,'setTotal',setTotalVal.val(),vals.val());
}
else{
vals = updateDenominationVal.val(getUpdatedVal * getDenominationVal);
updateDenominationVal.val(getUpdatedVal * getDenominationVal);
total = parseInt(setTotalVal.val()) + parseInt(vals.val());
}
console.log(vals.val());
setTotalVal.val(total);
} else{
updateDenominationVal.val(0);
}
});
});
});
This is the index.php
This Javascript is for random numbers and displays into 9 text boxes.
<script>
function GetRandom()
{
var myElement = document.getElementById("no1")
myElement.value = Math.floor((Math.random() * 1000) + 1);
var myElement = document.getElementById("no2")
myElement.value = Math.floor((Math.random() * 100) + 1);
var myElement = document.getElementById("no3")
myElement.value = Math.floor((Math.random() * 10000) + 1);
var myElement = document.getElementById("no4")
myElement.value = Math.floor((Math.random() * 1000) + 1);
var myElement = document.getElementById("no5")
myElement.value = Math.floor((Math.random() * 10000) + 1);
var myElement = document.getElementById("no6")
myElement.value = Math.floor((Math.random() * 1000) + 1);
var myElement = document.getElementById("no7")
myElement.value = Math.floor((Math.random() * 1000) + 1);
var myElement = document.getElementById("no8")
myElement.value = Math.floor((Math.random() * 1000) + 1);
var myElement = document.getElementById("no9")
myElement.value = Math.floor((Math.random() * 10000) + 1);
}
</script>
This javascript is take 9 text boxes value into array and sort list
<script>
function sortlist()
{
var captureNumb = document.getElementById("no1");
var captureNumb = document.getElementById("no2");
var captureNumb = document.getElementById("no3");
var captureNumb = document.getElementById("no4");
var captureNumb = document.getElementById("no5");
var captureNumb = document.getElementById("no6");
var captureNumb = document.getElementById("no7");
var captureNumb = document.getElementById("no8");
var captureNumb = document.getElementById("no9");
var captureNumb = document.getElementById("no1");
var numbers = captureNumb.value.split(" ");
captureNumb.value = numbers.sort(function (a, b) {
return a - b
}).join(" ");
}
</script>
</head>
<body>
<div class="form-inline">
<div class="col-xs-12">
<div class="form-group">
<input type="text" class="form-control" id="no1" name="no1" placeholder="No 1">
</div>
<div class="form-group">
<label for="exampleInputName2"></label>
<input type="text" class="form-control" id="no2" name="no2" placeholder="No 2">
</div>
<div class="form-group">
<label for="exampleInputName2"></label>
<input type="text" class="form-control" id="no3" name="no3" placeholder="No 3">
</div>
<div class="form-group">
<label for="exampleInputName2"></label>
<input type="text" class="form-control" id="no4" name="no4" placeholder="No 4">
</div>
<div class="form-group">
<label for="exampleInputName2"></label>
<input type="text" class="form-control" id="no5" name="no5" placeholder="No 5">
</div>
<div class="form-group">
<label for="exampleInputName2"></label>
<input type="text" class="form-control" id="no6" name="no6" placeholder="No 6">
</div>
<div class="form-group">
<label for="exampleInputName2"></label>
<input type="text" class="form-control" id="no7" name="no7" placeholder="No 7">
</div>
<div class="form-group">
<label for="exampleInputName2"></label>
<input type="text" class="form-control" id="no8" name="no8" placeholder="No 8">
</div>
<div class="form-group">
<label for="exampleInputName2"></label>
<input type="text" class="form-control" id="no9" name="no9" placeholder="No 9">
</div>
<br><br><br>
<div align="center">
<button type="button" class="btn btn-primary" onclick="GetRandom()">Populate</button>
<button type="button" class="btn btn-primary" onclick="sortlist()" >Sort list</button>
<button type="button" class="btn btn-primary">Primary</button>
</div>
</div>
</div>
How to click button sortlist and re-display follow by sort list?
tried to capture the value from 9 textboxes.
Your code need to be seriously looked at. You've got many repeated statements that could be solved with loops, and on every line where you redefine a variable, something like var myElement = ... two lines in a row, there is really no point in assigning it to a variable, as you never reference myElement and it's value is overridden on the next line.
In terms of what you're requesting regarding sorting, you need to dynamically insert them from some data structure.
<?php
$values = someGeneratingFunction();
$values = someSortFunction($values);
for($i=0;$i<count($values);$i++) {
echo "<input type=\"text\" class=\"form-control\" id=\"no" . $i . "\" name=\"no" . $i . "\" placeholder=\"No 1\">"
}
// Note the insertion of the ID values ("no1", "no2" etc.) using the loop instead of repeatedly typing the same thing.
?>
Keep in mind the above code doesn't use the entire HTML structure you've supplied, but you can use this as a general idea for how to achieve what you want. When you call a sort method, you can just re-run this code and it will just print all the elements in the array values in whatever order they've been put in.
EDIT
Consider the below JavaScript.
function sortList() {
var values = [];
for(i=1;i<10;i++) {
values.push(document.getElementById("no".concat(i)));
}
return values.sort( function(a,b) { return a-b } );
}
We initialize an array to hold all the elements identified by the IDs "no1", "no2" etc. Then we push them on, 1 by 1, in a for loop that accesses them all uses the indices (note this is what I was getting at, as this is better than repeating the same code 10 lines in a row, only altering a number.), and then we return our sorted array. Notice that we are passing a function as a parameter to when we call values.sort( function(a,b) { return a-b } ). This is because by default, the .sort() method sorts as strings, alphanumerically in ascending order. So the array [1, 3, 200, 15000] would be sorted as [1, 15000, 200, 3] which is quite clearly not in numeric order. By providing the additional function as a parameter, we tell it to subtract the two (it acts as our comparator) and then will provide us with accurate numeric results.