Selecting same element using class in JQuery [duplicate] - javascript

This question already has answers here:
Modify the value of each textfield based on original value using jQuery
(3 answers)
Closed last year.
I have lot of date fields in my application. IDs can't help, I want to format date fields using class. While trying to format the date, Holder2 date is also changed to Holder1's date, PFB
$(document).ready(function(){
$('.date').val($.format.date($('.date').val(), "MM/dd/yyyy hh:mm a"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.min.js"></script>
<html>
<head>
<title>Test</title>
</head>
<body>
<div>
Holder 1:<input class="date" type="text" value="Mon Feb 06 00:30:00 IST 2017"><br>
Holder 2:<input class="date" type="text" value="Sun Mar 12 11:06:00 IST 2017">
</div>
</body>
</html>
Current Output:
Holder 1: 02/06/2017 12:30 AM
Holder 2: 02/06/2017 12:30 AM
Expected Output:
Holder 1: 02/06/2017 12:30 AM
Holder 2: 03/12/2017 11:06 AM
PS: type is mentioned as text because if mentioned as date, chrome shows its own datepicker. Both my custom datepicker and chrome's are loaded at the same time. Help me out please. Thanks.

You need to do the elements one at a time, which you can do with an .each() loop, or, more conveniently, by providing a callback function to the .val() method. The function you provide will be called once for each element, and will receive the current value of the field as an argument; whatever value you return will be set as the value.
$(document).ready(function(){
$('.date').val(function(i, oldVal) {
return $.format.date(oldVal, "MM/dd/yyyy hh:mm a");
});
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.min.js"></script>
<html>
<head>
<title>Test</title>
</head>
<body>
<div>
Holder 1:<input class="date" type="text" value="Mon Feb 06 00:30:00 IST 2017"><br>
Holder 2:<input class="date" type="text" value="Sun Mar 12 11:06:00 IST 2017">
</div>
</body>
</html>

there is a formatting using css classes right in the documentation.
https://github.com/phstc/jquery-dateFormat
$(document).ready(function() {
var longDateFormat = "MM/dd/yyyy hh:mm a";
jQuery(".date").each(function(idx, elem) {
jQuery(elem).val(jQuery.format.date(jQuery(elem).val(), longDateFormat));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.min.js"></script>
<div>
Holder 1:
<input class="date" type="text" value="Mon Feb 06 00:30:00 IST 2017">
<br> Holder 2:
<input class="date" type="text" value="Sun Mar 12 11:06:00 IST 2017">
</div>

The $('.date') selector will apply the change to all jQuery elements matching that selector, but will get the val from the first element matching the query. To get the val from the element you'll be formatting, you can use jQuery's .each(), along with $(this), to make sure you're targeting the current matched element.
$(document).ready(function(){
$('.date').each(function() {
$(this).val($.format.date($(this).val(), "MM/dd/yyyy hh:mm a"));
});
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-dateFormat/1.0/jquery.dateFormat.min.js"></script>
<html>
<head>
<title>Test</title>
</head>
<body>
<div>
Holder 1:<input class="date" type="text" value="Mon Feb 06 00:30:00 IST 2017"><br>
Holder 2:<input class="date" type="text" value="Sun Mar 12 11:06:00 IST 2017">
</div>
</body>
</html>

you can not do like this, because at end you see the all inputs have same result, in fact the first result added to all inputs.
you should use each()
$('.date').each(function(index){
$(this).someMethod()
});

Related

JavaScript get UTC from local midnight

I have a date that comes from a Bootstrap DateTimePicker $('#datetimepicker').find("input").val() that has the format "mm/dd/yyyy".
<div class='input-group date' id='datetimepicker'>
<form autocomplete="off" onkeydown="return event.key != 'Enter';">
<input type='text' autofill="off" readonly class="form-control" />
</form>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
I'm trying to get the UTC date and time for the selected date, at midnight, using Moment js:
moment.utc($('#datetimepicker').find("input").val()).tz(timezone).format('YYYY-MM-DD HH:mm:ss')
For example, starting date from the picker is 01/21/2022 and the timezone is America/Phoenix which is UTC-7.
I should have 2022-01-21 07:00:00 but my code returns 2022-01-20 17:00:00.
What am I doing wrong? Is there a way to get the UTC time for a day at 00:00 time, just by knowing the timezone?
You have to create the timestamp in your local timezone first, and then convert it to UTC. You are doing it the other way around. Ie if I split up your code snippet, you are doing the following
let thedate = $('#datetimepicker').find("input").val();
let utcdate = moment.utc(thedate);
let localdate = utcdate.tz(timezone);
Thus, the timezone offset is, of course, added in the wrong direction ...
Try the following
function getTime() {
let thedate = $('#thedate').val();
console.log(thedate)
// create a timestamp in the respective timezone
let localdate = moment.tz(thedate, "America/Phoenix");
// convert it to utc
let utcdate = localdate.utc();
// format the timestamp
console.log(utcdate.format("YYYY-MM-DD HH:mm:ss"));
}
<script src="https://momentjs.com/downloads/moment.js"></script>
<script src="https://momentjs.com/downloads/moment-timezone-with-data.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="thedate" type="date">
<input type="button" onClick="getTime()" value="Get Time">

Javascript - get a date from an HTML input

I am currently trying to take the value from an HTML input (below)
<input type="date" id="dateInput" />
and put it into a javascript variable so I can use it for other things. I currently am using the code below.
var input = document.getElementById("dateInput").value;
var dateEntered = new Date(input);
But when I test those variables, it tells me that Input is "" and dateEntered is "Invalid Date".
I've tried the .valueAsDate instead of just .value as well. When I test those out, it tells me that Input is null and dateEntered is "Wed Dec 31 1969 19:00:00 GMT-0500 (Eastern Standard Time)" even though I entered today's date.
How would I fix this so that the javascript variables actually reflect the date I enter? I am using Google Chrome as my browser.
EDIT and UPDATE
For those who wanted my whole code, indentation is a little off sorry:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<title>Calculate Time</title>
<link rel="stylesheet" href="styles.css" />
<script src="modernizr.custom.05819.js"></script>
</head>
<body>
<header>
<h1> Calculate Time </h1>
</header>
<article align="center">
<div id="cities">
// My navigation links here (REMOVED)
</div>
<div id="caption">
Calculate the time elapsed since a date entered.
</div>
<div class="box">
<article>
<form>
<fieldset>
<label for="dateEntered">
Enter a Date
</label>
<input type="date" id="dateInput" />
</fieldset>
<fieldset class="button">
<button type="button" id="determineTime">Find Time</button>
</fieldset>
<fieldset>
<p>Time Elapsed is:</p>
<p id="time"></p>
</fieldset>
</form>
</article>
</div>
<div id="map"></div>
</article>
<script>
var input;
var dateEntered;
document.getElementById("dateInput").addEventListener("change", function () {
input = this.value;
dateEntered = new Date(input);
});
/* find and display time elapse */
function lookUpTime() {
// More code will go here later.
}
// add event listener to Find time button and clear form
function createEventListener() {
var submitButton = document.getElementById("determineTime");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", lookUpTime, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", lookUpTime);
}
document.getElementById("dateInput").value = "";
// clear last starting value on reload
document.getElementById("time").innerHTML = "";
// clear previous results on reload
}
if (window.addEventListener) {
window.addEventListener("load", createEventListener, false);
} else if (window.attachEvent) {
window.attachEvent("onload", createEventListener);
}
</script>
<script src="script.js"></script>
</body>
</html>
document.getElementById("dateInput").addEventListener("change", function() {
var input = this.value;
var dateEntered = new Date(input);
console.log(input); //e.g. 2015-11-13
console.log(dateEntered); //e.g. Fri Nov 13 2015 00:00:00 GMT+0000 (GMT Standard Time)
});
Basically you need to listen for the change of your date input, currently you were trying to get the value on load, when the picker has no date in it hence you get 'Invalid Date'
Make sure your script is executing after the DOM has fully loaded. To do this you can put your JS code in a function and call the function once the DOM has loaded, or just put your JS code at the end of your page, right before </body>.

Clear the value in a datetimepicker field

I'm sure this is simple and it's my understanding of jquery/javascript that is holding me back - but I can't get this to work.
All I need to do - is - When a button on the screen is clicked, clear some of the input field on the form back to their original values.
This is working fine, for all fields except a datetimepicker field.
Here is the relevant bits of code, that defines the input field :
<div class='form-group' id='START_DATEFormGroup'>
<label for='START_DATE' class='col-sm-2 control-label' data-toggle='tooltip' data-placement='top' title=''>Start Date</label>
<div class='col-sm-8'>
<div class='input-group date form_date col-sm-3' data-date-format='dd M yyyy' data-link-field='START_DATE' data-link-format='yyyy-mm-dd'>
<input class='form-control' size='16' type='text' />
<input type='hidden' id='START_DATE' name='START_DATE' />
<span class='input-group-addon'>
<span class='glyphicon glyphicon-calendar'>
</span> // group-addon
</span> // calendar
</div> // form_date
</div> // col-sm-8
</div> // form-group
I am initializing datetimepicker as follows :
function enableDatepicker(){
$( document ).ready(function() {
$('.form_date').datetimepicker({
format: 'dd M yyyy',
minView: 2,
autoclose: 1,
})
});
}
To clear the input fields down I have :
function clearActionForm(){
// code here to clear the various input fields to null or their initial values.
// Need statements to clear the datetimepicker field to null.
}
So, can someone give me the line(s) of code I need to insert into clearActionForm() in order to clear the START_DATE field to null.
Thanks.
If you are using the eonasdan datetimepicker use the following:
// clears
$("#form_date").data("DateTimePicker").date(null);
// updates with date
$("#form_date").data("DateTimePicker").date(new Date());
// or update with string
var myCoolDate = "27 05 1975";
$("#form_date").data("DateTimePicker").date(myCoolDate);
// or update with a moment
var moment = moment().add(2, 'd');
$("#form_date").data("DateTimePicker").date(moment);
Below is a demo of using different types of changes.
$(function() {
$('#datetimepicker1').datetimepicker({
format: 'dd M YYYY',
});
});
$('#clear').click(function() {
$("#datetimepicker1").data("DateTimePicker").date(null);
})
$('#date').click(function() {
var sysdate = new Date();
$("#datetimepicker1").data("DateTimePicker").date(new Date());
})
$('#string').click(function() {
var myCoolDate = "27 05 1975";
$("#datetimepicker1").data("DateTimePicker").date(myCoolDate);
})
$('#moment').click(function() {
var now = moment().add(2, 'd');
$("#datetimepicker1").data("DateTimePicker").date(now);
})
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>
<input type='button' id='clear' Value='Clear Date'>
<input type='button' id='date' Value='Set with date'>
<input type='button' id='string' Value='Set with string'>
<input type='button' id='moment' Value='Set with moment'>
use this line $('.form_date').data("DateTimePicker").clear()
Demo
Easy way to rest the selected date as well as highlighted date by below concept
$('#txtWQApprovalDate').datepicker('setDate', null).datepicker('fill');
Assuming that you are using the datetimepicker plugin from xdsoft.net/jqplugins/datetimepicker, one quick way to clear the datetimepicker's current value would be the following:
$('.form_date').val('');
As an alternative (this sets the value of the datetimepicker to the current time):
$('.form_date').datetimepicker({
value: (new Date()).toLocaleString()
});
This value does not not match the format of the datetimepicker, but will be converted to the correct format automatically when the datetimepicker is used.
If you are using the eonasdan datetimepicker use the following:
// clears
$j(".form_date").data("DateTimePicker").setDate(null);
// updates to now
$j(".form_date").data("DateTimePicker").setDate(new Date());
// or update to a given date
var myCoolDate = "05/27/1975";
$j(".form_date").data("DateTimePicker").setDate(myCoolDate);

Uncaught Type Error: Cannont set Property 'valueAsDate' of null

I am getting this weird error that I attempting to debug. I have an input field that has the current time pre-displayed as the value. When I run the page I get the Uncaught Type error referring to the JavaScript file line number 8 (document.getElemntByID("theTime").valueAsDate=b;)
Is it trying to say ValueAsDate is not defined? What do I put in place of it? Any help is most appreciated.
html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" content="HTML,CSS,XML,JavaScript">
<script src="Scripts/jquery.js" type="text/javascript"></script>
<script src="Scripts/Global.js" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" href="Styles/Design.css">
</head>
<body>
<form action="" method="post">
<fieldset>
<table border="0px" >
<tr>
<td colspan = "2" id="formHeader">
Select Date and Time
</td>
</tr>
<tr>
<td class="spaceUnder" id="formBody">Date: <input type="date" id="theDate"></td>
<td align="center" class="spaceUnder" id="formBody">Time: <input type="time" id="theTime" ></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
JavaScript
$(document).ready(function() {
myTimer();
});
function myTimer() {
var a = new Date();
var b = new Date(a.getFullYear(), a.getMonth(), a.getDate(), a.getHours() - 8, a.getMinutes());
//$("#theTime")[0].valueAsDate = b;
document.getElementById("theTime").valueAsDate =b;
}
Its type is time, not date
<input type="time" id="theTime">
"document.getElemnetById("theTime)" is TIME
var b = new Date(a.getFullYear(), a.getMonth(), a.getDate(), a.getHours() - 8, a.getMinutes());
b is DATE.
Try something like this,
b.setTime(document.getElementById("theTime"));
b.setHours(b.getHours() - 8);
The question should have been how to set input type date and input type time with current values in javascript.
And this just so that any one who searches this question in future may get help.
Because I did not find any answers on SO related to this.
Input type date expects date in this format yyyy-mm-dd.
Input time type expects time in this format hh:rr:ss format.
So the following function should do the task.
function myTimer() {
var dateObj = new Date();
document.getElementById('theDate').value = dateObj.toISOString().slice(0,10);
document.getElementById('theTime').value = dateObj.toTimeString().slice(0,8);
}
But these features are not yet fully supported in all browsers.
I tested it in chrome and safari and it is working fine.

jquery datepicker code not working (set specific date as default)

I am trying to set the date to a specific one on page load so I'm trying this code:
<script type="text/javascript">
$(document).ready(function() {
var queryDate = new Date();
queryDate.setFullYear(2009,11,01);
$('#date').datepicker({defaultDate: queryDate});
$("input[type='submit']").click(function(e) {
e.preventDefault();
$.post("s.php", $("form").serializeArray(), function(message) {
window.location="v.php"
});
});
});
</script>
//The form part where is displays the datepicker:
<form action="#" method="POST">
<div data-role="fieldcontain">
<label for="date">Date:</label>
<input type="date" name="date" id="date" value="" />
<input type="submit" value="submit" />
</div>
</form>
The problem is that nothing's changing ... the default is still the current date :o/
Any ideas anyone please?
UPDATE: Tried this code:
var queryDate = new Date(2009,11,01);
$('#date').datepicker({defaultDate: queryDate});
$('#date').val(queryDate);
And the date is appearing in the input box but the calendar is not in the right month nor date ... Moving foward but still not working.
I'm not sure sure the suggested answer here is not working. As I have tested it display on the right month and year, but only not highlighted the date. This could be because the date format.
Try adding this code to have a default value on your date.
$('#date').val(queryDate);
Then you may see that the format is different with the date in date-picker. If you manage to set the right format with date-picker, you get the things you wanted.
Umm what if you tried this
new Date(year, month, day, hours, minutes, seconds, milliseconds)
var queryDate = new Date();
queryDate.setFullYear(2009,11,01);
$('#date').datepicker({defaultDate: queryDate});
Then the datepicker knows its a date object and how to handle it.
EDIT
Ok - all i did was copy the code exactly as you got it here several posts the same suggestion- and the code you edited. Added tags- inlcuded jquery and jquery ui..
I see no problem- the defuatl date is 2009.
</head>
<script src="jquery.min.js" type="text/javascript"></script>
<script src="jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
var queryDate = new Date();
queryDate.setFullYear(2009,11,01);
$('#date').datepicker({defaultDate: queryDate});
$("input[type='submit']").click(function(e) {
e.preventDefault();
$.post("s.php", $("form").serializeArray(), function(message) {
window.location="v.php"
});
});
});
</script>
</head>
<body>
//The form part where is displays the datepicker:
<form action="#" method="POST">
<div data-role="fieldcontain">
<label for="date">Date:</label>
<input type="date" name="date" id="date" value="" />
<input type="submit" value="submit" />
</div>
</form>
</body>
Result (no styles sheet attached)
Working example- tell me what is wrong
http://jsfiddle.net/ppumkin/nptgn/
Try this
var queryDate = new Date(2009,11,01);<br/>
$('#date').datepicker({defaultDate: queryDate});
I was having a similar problem, I solved it like this
$('.datepicker').datepicker({dateFormat: "yy-mm-dd", defaultDate: "+3m"} );
Try this
$('#mydate').val("2009-11-01");

Categories

Resources