JavaScript split input's attribute into array and output - javascript

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="">

Related

How to set a value to an input that is smaller than min or larger than max?

EDIT: The issue was simply that some of the data I was attempting to place into the input was in an incorrect format. Look at the accepted answer to read more.
I am working with an input field that has the type="datetime-local". I have also set min and max values to said input. I would like to still add values to it through JavaScript that break these constraints, being smaller than the minimum date or larger than the maximum date. However, currently just setting the value (in this case a value smaller than min), causes the time portion of the input to become blank, like so:
datetimeInput = document.createElement('input');
datetimeInput.setAttribute('type','datetime-local');
datetimeInput.setAttribute('step','1');
datetimeInput.setAttribute('min', minTime);
datetimeInput.setAttribute('max', maxTime);
if (data) {
datetimeInput.value = data.time;
}
Every country or region has its own datetime format. The default value format for a datetime-local type <input> tag in my region is:
YYYY-MM-DDTHH:MM
If I was to set the value of my <input> element to the following:
datetimeInput.value = "2017-12-31T00:00";
This will result in the value being assigned and the input tag will now show you the datetime value assigned through javascript.
See this working in the following snippet. You can then use your region's default format to set the value:
datetimeInput = document.createElement('input');
datetimeInput.setAttribute('type', 'datetime-local');
datetimeInput.setAttribute('step', '1');
datetimeInput.setAttribute('min', "2018-06-07T00:00");
datetimeInput.setAttribute('max', "2018-06-14T00:00");
datetimeInput.value = "2017-12-31T00:00";
document.getElementById("main").appendChild(datetimeInput);
<div id="main"></div>

JavaScript suppress date format warning

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.

Adding time to jQuery datepicker() function

I have a input field which I want to fill with date and time in format yy-mm-dd hh-mm-ss, because I'm sending this information to my databases column with DATETIME (or similar) data type. I made this work with two inputs - one textfield I filled with datepicker() and other was <select> list with predefined values for time. Today I was coding another functionality in php and I didn`t like my situation with date and time, so I made javascript code like this:
<script type="text/javascript">
$(".datepicker").click(function(){
var a = "yy-mm-dd ";
var b = prompt("Ievadi laiku formātā hh-mm-ss", "00-00-00");
var c = a.concat(b);
$(".datepicker").datepicker({dateFormat: c});
});
</script>
So when I click on the input field I get a prompt where I type time and press enter. This is when I'd like to choose a date from the calendar but as datepicker actually works at the same time when prompt shows up (on click), then argument c doesn't exist at this time and calendar doesn't show up because dateFormat is invalid. If I click once again on the input field, I get another prompt and after the second prompt calendar shows up, but datepicker uses the format I was trying to set the first time not now. So if I entered "00-00-00" for the first time and "00-10-00" for the second, than after choosing the date I get "mydate 00-00-00" and not the actual time I entered this time. I've seen similar posts here but it didn't help me. There was a post of getting current time and appending to the date but I guess this is different. Should I use some other method to enter the time and then add it to date as I was trying to do it or is there a way to give my variable c a value before datepicker works? I`ll appreciate your suggestions.
<script type="text/javascript">
$(".datepicker").click(function(){
var a = "yy-mm-dd ";
var b = prompt("Ievadi laiku formātā hh-mm-ss", "00-00-00");
var c = a.concat(b);
if (c.length > 0){
$(".datepicker").datepicker({dateFormat: c});
}});
</script>
If statement solved this one. But it doesnt work every time. Ill check this tomorrow.
EDITED: this works - https://jsfiddle.net/gne64yd5/20/

Outputting an input value to a span

I uilt a simple page where a user selects a series of dates via a jquery datepicker (It has to support IE8). There's a botton that executesa function in JS that outputs these values to input boxes in a paragraph. Now this works perfectly, my problem is that the end user will be copying and pasting this info and the textbox lenght is often longer than the date string. I know that i can avoid this mess by using and innerHTML. I have been looking at several examples on this forum but I am not having any luck.
function sayHi(){
// THIS is WHERE input VARIABLES are set, followed by the OUTPUT
//this defines the First Week of Sickness Paid Start Date
var BPCName = document.getElementById("BPCName");
var OUTBPC = document.getElementById("OUTBPC");
var name = BPCName.value;
OUTBPC.value = " " +name+ ""
I essentially want "OUTPBC.value" to go within the span when the function is run. Should this appear as part of the sayHi function?
<script>
document.getElementById("OUTBPC").innerHTML = OUTBPC.value;
</script>
and should my paragraph look like
The Period of paid sickness began on
<span id=OUTBPC> </span>,<pP
You need to set innerHTML not value.
OUTBPC.innerHTML = " " +name+ ""; //replaces OUTBPC.value = " " +name+ "" in sayHi

JavaScript - Input a date then autopopulate next field with difference

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.

Categories