Whenever I try to reset a date input using JavaScript, like so:
//input_id is an id of a date input
document.getElementById(input_id).value = "0000-00-00";
I get a warning in the console:
The specified value "0000-00-00" does not conform to the required format, "yyyy-MM-dd".
Does anyone know a way to suppress this warning so it won't show? The JS keeps on running smoothly but I want to get rid of these warnings.
If you have another way of resetting a date input (without raising a warning) I will be happy to hear.
Thanks in advance.
You're getting the warning because years, months, and days start at 1, not 0. 0 is an invalid value for all of them. But there's a simpler way to reset an input element..
You can just set the value to the empty string which is the initial default value.
var di = document.createElement("input");
di.type = "date";
console.log(di.value); // outputs ""
document.body.appendChild(di);
// change the value if you want
// to reset:
di.value = "";
You can assign a empty string value
document.getElementById(input_id).value = "";
At the bottom of your Javascript call
console.clear();
This clears all warnings and errors from your console.
You can also replace console.warn with your own code like:
console.warn = function () { };.
NOT recommended because you will not get any warnings to your console this way.
Related
I have a little problem with my jQuery script: instead of counting up all variables, the script puts them next to each other. How do I count up the variables? (I am new to jQuery, so maybe I overlooked something or made a stupid mistake).
This is the line of code that should count up the variables.
totalcost = ((commissioncost + paypalcost) + qrticketcost);
http://jsfiddle.net/bsuh5q8k/1/
Thanks.
Often when you retrieve a value from a field using jquery's .val(), you'll get the string value (String type) instead of the numeric value you desire here. For instance, the field value may be 37.50, but you're getting "37.50" from .val()
So when you do this:
commissioncost = $('input[name=price]').val();
You'll get the String value.
So instead, try this:
commissioncost = Number($('input[name=price]').val());
This will convert/cast the value into a Number for you.
Also, a word of caution: just be sure whatever value is in that field, it can be evaluated as a Number, otherwise comissioncost will equal "NaN" (not a number) and will give you the same grief you're experiencing now. The rudimentary method to check if the type conversion was successful is:
commissioncost = Number($('input[name=price]').val());
if(isNaN(commissioncost)){
// oops, value wasn't a number!
}else{
// hooray! value was a number (most of the time - but that's a longer discussion)
}
commissioncost is being treated as a string. So when you add it thinks you're wanting to concatenate.
When you pull it from the input, explicitly tell Javascript that it's a number/float.
commissioncost = parseFloat($('input[name=price]').val());
Codepen Link
JSFiddle Link
The goal:
Create dynamically refreshing output with split year-month-day from the input field.
Description:
Do not pay attention to any code at CodePen above the comment at line 40;
I got an input. Whenever the user picks a date with the initialized datepicker, the input gains data-date attribute with YYYY-mm-dd format. Ok, perfect.
I want to create an output to a div based on this data-date attribute.
So I wrote the following code:
function summaryOutput() {
var output = $( '#output' );
var end = $( '#end' );
end.on('change', function() {
var endString = end.attr('data-date');
var endSplit = endString.split('-');
var year = endSplit[0];
var month = endSplit[1];
var day = endSplit[2];
output.text(year);
});
}
It is pretty straightforward.
This function is not invoked in the codepen
Invoke it and try to select a date and see an error:
Uncaught TypeError: Cannot read property 'split' of undefined
And what is more, data-date attribute cease to apply.
What is more confusing, it works in the console. I mean, if you select a date in the datepicker and then step by step initialize all the variables and then will, for example, see what is in the month variable, you'll get the result.
But it ceases to work in the real document.
So am, where am I wrong?
You need to add a data-date attribute in your input tag.
Change the input tag to look like this:
<input type="text" id="end" data-date="">
Here's the issue with Podio. I have a calculation field that is set to return a date and it does that well if I only enter a reference to a date field from the item. What I want is for the calculation field to return a null date (as part of an IF statement) and thus leave or make the field empty (and therefore not show up in the calendar).
Something like this:
var date = DateFieldFromPodioItem;
if (whatever) {
moment(date).add(2, "weeks").toDate();
}
else {
//RETURN NULL HERE
};
I have tried setting var zero = null and have it return that. Which yields me an Invalid date error.
I also tried using .setFullYear(null,null,null) along with .setHours(null,null,null,null) to set date and return that. I set date to 1 January 0001 12:00:00.000 AM as was suggested somewhere (I forgot where I read that). The first got me a rather unfriendly: Invalid value datetime.datetime(1753, 9, 12, 22, 43, 41, 128000) (datetime): Dates before year 1900 are not supported. The second did too, with slightly different numbers within the ().
I even tried the rather silly idea of entering no code within else, but that also returns Invalid date.
Any ideas?
----EDIT----
Turns out that even while Podio shows the message Invalid date it lets you save the field anyway and when changing field values so if=false it shows no longer a date in the calculation field. Thanks to Rainer Grabowski for pointing that out to me. If someone #Podio reads this, perhaps fix that?
I'll leave this here to perhaps help someone else, as I have found the answer to my questions on here rather often.
Should work, but I didn't test:
var date = DateFieldFromPodioItem;
var returnValue = null;
if (whatever) {
returnValue = moment(date).add(2, "weeks").toDate();
}
returnValue;
Hi this is making me nuts. I am not a developer. Trying to get this to work.
User puts in a date (hire date) into form using Date object (calendar)
Next field should take that date and subtract todays date to get the length of employment.
But I get undefined in the field AND my original hire date disappears.
Here is what I have, help please, much appreciation!
//grab date of hire
try{document.getElementById("dData_DOH").onchange = custom_calculateDate;}catch(e){}
//not sure if necessary - field that the difference should go to
try{document.getElementById("dData_LengthEmp").onblur = insertDate;}catch(e){}
//Function to grab input hire date
//Create variable for now
//Create variable for difference
function custom_calculateDate(){
var hireDate = document.getElementById("dData_DOH").value = "";
var timeNow= new Date();
var diff = Math.abs(timeNow - hireDate);
document.getElementById("dData_DOH").setAttribute('value', custom_calculateDate());
}
//Function to get the difference into the LengthEmp field
function insertDate() {
document.getElementById("dData_LengthEmp").setAttribute("", custom_calculateDate());
}
I know this is completely wrong, as I said I am not a developer or programmer, I cannot figure out how to get this information into this field and get my original field to still show.
Thank you for reading this!
Use value instead of setAttribute
document.getElementById("dData_DOH").value = custom_calculateDate();
Wow wow wow.
I'll try to rewrite your code by giving you explainations about why:
// Firstly, the onchange event doesn't work on IE for text inputs, prefer onblur
document.getElementById('dData_DOH').onblur = function(e) {
// Now let's get some variables
var hireDate = this.value, // "this" refers to the element that triggered the event
now = new Date(),
// You were on the right track for the difference, almost!
diff = Math.abs(new Date(now.getTime() - hireDate.getTime()))
// Finally, just don't change the original field, but the one you wanted to modify
document.getElementById('dData_LengthEmp').value = diff.toTimeString() // Get the time as a readable format
}
I haven't tested the solution, but it should get you on the track.
Btw, don't use try/catch.
I ran into a problem with an object which I'm trying to modify. The object has a certain amount of keys in the format key_yyyy-mm-dd. When certain inputfields lose focus, I trigger a function to modify the object. This function is as follows:
function updateHotelBooking()
{
$(".no_hotel").each(function(i) {
var day = $(this).attr('name').match(/\[(.*?)\]/)[1];
hotelBooking["key_" + day] = parseInt($(this).val());
});
}
.no_hotel are the textboxes that trigger the function, and they also provide a value which I want to put in my object.
Now, say I put 3 in my first text box, a console.log will return the following object:
Object
key_2011-08-21: 3
key_2011-08-22: 0
key_2011-08-23: 0
key_2011-08-24: 0
key_2011-08-25: 0
However, the next time I put something in the textbox (or another textbox that should trigger the function), it DOES trigger, however the object returned remains the same. So instead of changing the first number to, say, 5, it will just return 3 again.
I have no idea why. My code seems pretty straightforward, and a console.log of day and $(this).val() returns the right values. It's just my object that doesnt get updated.
Does anyone have any idea? Thanks a lot!
EDIT:
hotelBooking is initialized right after $(document).ready():
var hotelBooking = {};
The method that calls updateHotelBooking is the following:
$(".roomrequest").blur(function()
{
updateHotelBooking();
});
EDIT2: JSFiddle: http://jsfiddle.net/pBYeD/2/
it has to do with something with the console rather than your code, if you change the logging code to this, you will see that you have the correct values:
function updateHotelBooking()
{
$(".no_hotel").each(function(i) {
var day = $(this).attr('name').match(/\[(.*?)\]/)[1];
hotelBooking["key_" + day] = parseInt($(this).val());
**logObject(hotelBooking);**
});
}
function logObject(hotelBooking){
for(var i in hotelBooking){
console.log(i+": "+hotelBooking[i]);
}
console.log("------");
}
Are you sure the problem does not come from the debugger output?
As far as i can see in my chrome output, if i let the fiddle as is, the object doesn't appear to change in the console (just the number on the left takes a +3). However if I add something like console.log(hotelBooking["key_" + day]); just before or after, it's shown as changing.