For the site I am developing, I use a form to update the different fields of a model.
Some of those fields need to be updated according to the values of others.
For example, each instance of a Task, has a start date, an end date, and a length which have to verify the following : End = Start + Length (where weekends are not counted, but that is a secondary issue).
So one of the functions I am trying to write would do :
When the user changes the value of the input Start_date
Get that date from the input field
Get the value of the field Length
Update the value of the input "End date" with (Start_date + Length)
The three inputs concerned by my example have the following IDs : id_start, id_length, id_finish.
Here is what I have written, but which doesn't work at all (nothing visible happens...) :
<script>
$( "#id_start" ).change(function() {
var start = new Date();
var finish = new Date();
var numberOfDays = document.getElementById('id_length').value;
start = document.getElementById('id_start').value;
finish.setdate(start.getDate()+document.getElementById('id_length'))
$('#id_finish').val(finish);
});
</script>
Any hint at a solution to make it work would be hugely appreciated.
Let's look at what your code is actually doing.
var start = new Date();
Here you create a new Date object.
start = document.getElementById('id_start').value;
Here, you change the value of start to the value of the DOM element with the id = 'id_start'. The problem is, this value isn't a Date object. Even the new HTML Date input type (which isn't supported by Firefox or IE) will only give you a string when you pull it's value. So you've created a new Date object, and then you throw it out immediately.
So now start isn't a Date, but a string. In this line:
finish.setdate(start.getDate()+document.getElementById('id_lenght'))
You're attempting to call the undefined .getDate() on a string object, so you'll get an error.
Here's what you need to do. That string (assuming it's in ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS) can be used to create a new Date.
start = new Date(document.getElementById('id_start').value);
Now start is actually a date object, and you can add the length in days to get your end date.
Of course, you'll want to make sure the input is in an acceptable format! There's a lot of 'date picker' options (jQueryUi, for example, has a datepicker), and if you're only interested in supporting Chrome, the works well.
Related
I have a datetime-local input (and jQuery) and I'm trying to figure out how I can essentially autofill the time of the input. The value is not required so I can't just set a default datetime, but I need the time to default to a predetermined time (let's say 10:00 PM) if a user picks a date. (Other times are valid but extremely rare)
I tried to pull the incomplete value, but that appears to be impossible due to W3C's sanitation of the value (per this SO thread and testing)
Is this even possible or will I need to abandon datetime-local?
you can set it as value
var selectElement = $('#date-time');
var date = '2020-03-19'; // default date
selectElement.on('change', (event) => {
date = selectElement.val().split('T')[0];
selectElement.attr('value', date+'T22:00"');
});
Is it possible to compare dates with Knockout observables and jQuery Validation? I have a StartDate and an EndDate, both observables. I want to validate that the EndDate is always greater than the StartDate.
I've tried the addMethod feature but I can't seem to pass in self.StartDate. It doesn't seem that the addMethod accepts KO observables, so I have to pass in the string ID, "#StartDate".
$.validator.addMethod("dateGreater", function(value, element, params){
var endDate = new Date(value); // this returns incorrect date.
var startDate = new Date($(params).val());
return this.optional(element) || startDate < endDate;
}, "The End Date must be greater thatn the Start Date.");
The problem with this code is that when the user selects a date with the DatePicker, the EndDate returns the previous date, not the currently selected date, and since the StartDate is not an observable being validated, if the user changes it, the validation doesn't fire.
I guess my question really is, can this be done with jQuery Validation, or should I be using Knockout-validation?
I created a simple jsfiddle that shows what I'm trying to accomplish. http://jsfiddle.net/kahanu/htqfa1qw/6/
This answer follows the approach of keeping jquery-validation outside of KO. I think this is OK, because you don't lose any magic; jquery-validation has its own framework for tracking changes and it keeps KO and jquery-validation separate, which is simple.
Here is your fiddle, with this approach applied:
http://jsfiddle.net/htqfa1qw/7/
The fixes were:
jquery-validation requires names in the input elements
These names then correspond with the keys in the rules object.
Param passing is weird and the docs don't explain it well!
So your rules object now looks like this:
EndDate: {
required: true,
dateGreater: {
param: "StartDate"
}
}
which is saying we want the <input name="EndDate"> to be greater than the <input name="StartDate">
We then modify the rule so that it gets the value directly from the DOM without needing to go via KO:
var start = new Date($("[name="+param+"]").val());
If you did want to do it via KO by passing in the observable as you describe, then you could do this:
http://jsfiddle.net/htqfa1qw/9/
Instantiate your data model before applying it:
var dm = new DataModel();
ko.applyBindings(dm);
Then alter the validation rule to lookup the method by the param, and call it:
$.validator.addMethod("dateGreater", function (endDate, element, param) {
var end= new Date(endDate);
var start = new Date(dm[param].call());
return this.optional(element) || start < end;
}, "Start Date must be less than End Date.");
(With ref to the comments) Once it is working with the bootstrap-datetime widget, you need to be careful about how the widget changes the input value, and how it's method of changing the value ineracts with both the jquery-validation framework and also the KO framework, both of which rely on change events.
In your fiddle the problem seems to be that jquery-validation gets triggered with the old date value before the widget successfully loads the new value into the input. Hence you see validation happening on the old value... The quick fix seems to be to call jquery-validation's valid() method, to trigger a manual validation, in the event handler you already have:
$el.datepicker(options).on("changeDate", function (ev) {
var observable = valueAccessor();
observable(ev.date);
$(this).datepicker('hide');
// Poke jquery validation to validate this new value.
$("#date-form").valid();
});
Demo here:
http://jsfiddle.net/htqfa1qw/12/
In this fiddle there's some console.logs and you can track the sequence:
validation is called with the old value (the "Start date..." log statement)
your event handler kicks in with the new value (the "changeDate" log statement)
We manually call valid() and validation is called with the new value (the 2nd "Start date..." log statement)
var curRate = nlapiCreateRecord("customrecord_currency_exchange_rates",{recordmode: 'dynamic'});
serverDt = "09/25/2013 06:00:01 am"
var timezone = compConf.getFieldText('timezone');
curRate.setDateTimeValue('custrecord_effective_date' ,serverDt ,timezone);
nlapiSubmitRecord(curRate);
Hello I try to set custrecord_effective_date field which is a date/time type. But after the execution it gives an error below.
How can I set this field?
thanks for help.
INVALID_FLD_VALUE You have entered an Invalid Field Value 09/25/2013 06:00:01 am for the following field: custrecord_effective_date
Although this is an old post and the original question is about SuiteScript 1.0, I came across this page looking for the same INVALID_FLD_VALUE error with the date/time field but in SuiteScript 2.0, and since the solution ended up being different I wanted to share it for future readers.
In SuiteScript 2.0, setting a date/time field simply requires a JavaScript date object. Below is an example within a before submit user event context.
context.newRecord.setValue({
fieldId : 'custrecord_myfield',
value : new Date()
});
For setting Date/Time Field values using SuiteScript 2.O.
First Use 'N/format' module and 'N/Record' Module.
Create a normal Javascript Date Object.
Format the Date Object to DateTime Object.
And use Record.setValue() method for setting the datetime value.
Example:
var d = new Date();
var formattedDateString = format.format({
value: d,
type: format.Type.DATETIMETZ
});
record.setValue('yourDateTimeFieldId',formattedDateString );
For anyone that may be stuck with a SuiteScript 1.0 script trying to populate a date/time field and the existing solutions don't work for you, you can try using NetSuites nlapiDateToString method. Apparently the date/time field wants a string.
Example:
var record = nlapiCreateRecord('your record type');
record .setFieldValue('your date field id', nlapiDateToString(new Date(), 'datetimetz'));
nlapiSubmitRecord(record, false, true);
The SuiteScript 1.0 reference for more detail:
Hi thanks for answers after posting the question i checked the Form of record type and when i checked for the field 'custrecord_effective_date' I noticed that the date format must be 'DD/MM/YYYY HH:MM:SS' so when i changed it worked.
If you look at the NetSuite WSDL file, you will find the dateTime declaration:
<xs:simpleType name="dateTime" id="dateTime">
<xs:documentation
source="http://www.w3.org/TR/xmlschema-2/#dateTime"/>
Go to the URL and look at the source:
3.2.7 dateTime
[Definition:] dateTime values may be viewed as objects with integer-valued year, month, day, hour and minute properties, a decimal-valued second property, and a boolean timezoned property. Each such object also has one decimal-valued method or computed property, timeOnTimeline, whose value is always a decimal number; the values are dimensioned in seconds, the integer 0 is 0001-01-01T00:00:00 ...
So the format you are looking for is:
2013-09-25T06:00:01
I just pushed a dateTime to NetSuite and it worked.
Import N/format to your script and use one of the date format types:
DATE
DATETIME
DATETIMETZ
var parsedDate = format.parse({
value: '23/12/2010',
type: format.Type.DATE
});
The code looks ok
Are there any restrictions on the date field such that you can't set a date in the past?
Also your serverDt is the same value as the Netsuite help. Did it copy cleanly? What happens if you cut that string and type it directly?
And finally are you sure you have a datetime field and not a date field. If I apply your code to a date field I get the same error.
Little addition on the existing ans.
Error type -
type: "error.SuiteScriptError",
name: "INVALID_FLD_VALUE",
message: "You have entered an Invalid Field Value 2017-07-13T08:21:12.411Z for the following field: custrecord_lastrundate",
The value need to be set as a java script date() object. Even the simple same string of js date will throw error. If you are using moment then below code will work perfectly. Sample for adding next days.
var now = moment();
now.add(1,'days')
fetchRecord.setValue({
fieldId : 'custrecord_lastrundate' ,
value : new Date(now),
ignoreFieldChange : true
});
This is related and the other 2.0 answers are correct for Date/Time fields. However I was trying to set the incident time on the case record which is just the time field, and you have to do something like this:
let incidentTime = new Date(0, 0, 0, incidentDate.getHours(), incidentDate.getMinutes());
Notice - its still a Date object, but the Y, M, D values have to be zeroed for it to work.
Ahh Netsuite - you couldn't just do that behind the scenes yourself..
Please let me know if someone has a different solution.
I am creating a interactive calendar using FullCalendar but I have run into a nice to have snag.
When the person makes the hour range selection (click and drag) I have a dialog open and allows the user to title their event and modify the date/time selection if needed. What I would like is to re-render the selection with the new date/time selection from the dialog if it changes.
Currently when I run the select method my selection area is just removed from the view, I want it to stay and be updated to the current selection.
Here is my code
$('#UserCalendarToHour, #UserCalendarToMin').change(function(){
var allDay = false;
var startDate = new Date($('#UserCalendarFromDate').val()+' '+$('#UserCalendarFromHour').val()+':'+$('#UserCalendarFromMin').val());
var endDate = new Date($('#UserCalendarToDate').val()+' '+$('#UserCalendarToHour').val()+':'+$('#UserCalendarToMin').val());
if($('#UserCalendarAllDay').is(':checked')){
allDay = true;
}
$('#calendar').fullCalendar('unselect');
$('#calendar').fullCalendar('select',startDate.toString(),endDate.toString(),allDay);
});
Now what am I missing.
The select method is expecting startDate and endDate as Date objects. You're converting them to text. Also, according to docs,
allDay is a boolean indicating if entire days were selected (days in
month view or the "all-day" slot in the agenda view) or time slots
were selected.
So if you are selecting time slots you need to set it to false.
You'll see it more clearly in the select callback documentation. The same type for arguments seem to apply for the method. It took me a while to realize it. You may get confused with, for instance, the Event Object attributes, which have similar names but are of different type. See it here:
http://arshaw.com/fullcalendar/docs/selection/select_callback/
I have the following code:
http://jsfiddle.net/SPWWx/
I'm completely new to javascript, this is my first time using it. The values of the HTML selects MUST be 01,02 etc, that's why I had to use a big long if else statement. The values have to be submitted to an application on a server, which is extremely fussy about what way it takes in values.
Why won't it set the day as 15 (today) in the select box?
You have a few issues, you're not including jQuery on the left, the element has a name not an ID or CID, so it needs to be id="CID" or your selector needs to be select[name='CID']. Last, you need to pass a string to .val() to get the result you want, otherwise it's trying to set it to "4", which doesn't equal "04".
You can shorten all your code down to this though:
var day = new Date().getDate().toString();
$("#CID").val(day.length == 1 ? "0" + day : day);
You can test it here, also as Jamiec points out, you want .getDate() to get the date of the month as opposed to .getDay() which is of the week.
because the element's name is CID, not it's id! $('#CID') selects the element with the id CID.