I have the following function that produces numbered input fields with ids and names of the current timestamp they're were created. I'm trying to attach a datepicker to each one created, hence the unique/timestamp id's.
Can anybody suggest a way for me to go about doing this?
I believe the datepicker function needs to be produced under each input field created but I don't know how to produce a JavaScript function with JavaScript. I'm thinking maybe I can use jQuery's load() function and call a PHP script that produces a unique function and loads it into a div. Is that the best way to tackle this? Thanks!
<script>
var number = 0;
var num;
$('#add_date').click(function(event) {
number++;
var d=new Date();
var year = d.getFullYear();
var day = d.getDate();
var month = d.getMonth() + 1;
if (month<10){var month = "0"+month;}
if (day<10){var day = "0"+day;}
var fullyear = month+"/"+day+"/"+year;
num = event.timeStamp
$('#box').append( number+". <input type='text' id='" + num + "' name='" + num + "' value='"+ fullyear + "' size='10'/><br><br>");
var idtag = "#"+num;
});
</script>
Why not just set up the datepicker when you create the input?
var picker = $("<input/>", {
type: 'text',
id: num,
name: num,
value: fullyear
}).datepicker();
$('#box').append(number).append(picker);
Also you should make "id" values that look like valid identifiers instead of plain numbers.
Look at #Pointy's answer for an actual solution, he was quicker than me, my answer will not actually solve your problem, I just would like to mention a few points to note.
Try to indent your code properly, so it's easy to read for you after looking at it in a month's time. You might know now what it does exactly, but it will be a pain to figure it out in the long term.
As unlikely as it is, it can't be guaranteed that the same event won't fire twice in the same millisecond, I would avoid using event.timeStamp for generating unique IDs. It's just a personal preference though, it will probably never happen, I just don't like to rely on timers for uniqueness. You have your incrementing number variable already, you should use that, that will definitely be unique.
When writing HTML into a string, I would rather use the proper standard markup. Use ' as your string boundaries and " for your HTML attributes.
Lastly, inside your if(month<10){...} condition, don't redefine the variable you have already defined within your function. It would probably not throw an error or have any negative effect, but we can only thank the current forgiving javascript implementation for that, redefinition should not be allowed in the same scope.
Finally make sure you put all your jQuery initialisation code into the jQuery ready function to make sure the DOM and jQuery itself has fully loaded.
And sorry for the rant... ;)
$(function(){
var number = 0;
$('#add_date').click(function(event) {
number++;
var d=new Date();
var year = d.getFullYear();
var day = d.getDate();
var month = d.getMonth() + 1;
if (month<10) month = "0"+month;
if (day<10) day = "0"+day;
var fullyear = month+"/"+day+"/"+year;
// Insert #Pointy's solution in here...
});
});
You can add a fict
<input type='text' id='" + num + "' name='" + num + "' value='"+ fullyear + "' size='10' class='fake-class'/>
And then, you can load the datepicker object like this:
$('.fake-class').each(function(){
$(this).datepicker();
});
Hope it helps
Just a little correction about the variable num and number, #Pointy was using num and #DarthJDG was using number. Here is the complete code that worked for me
In Script:
var num = 0;
$('#btn').click(function(event) {
<!-- Set the default date to be todays date, can be removed for blank-->
num++;
var d=new Date();
var year = d.getFullYear();
var day = d.getDate();
var month = d.getMonth() + 1;
if (month<10) month = "0"+month;
if (day<10) day = "0"+day;
var fullyear = month+"/"+day+"/"+year;
<!-- End -->
var picker = $("<input/>", {
type: 'text',
id: num,
name: num,
value: fullyear
}).datepicker();
$('#holder').append(num).append(picker);
}
And in the HTML:
<input type="button" id="btn" value="button">
<div id="holder">
</div>
Related
I'm new to javascript so I apologize if this is a very basic question.
I am building (Drag & drop) forms for user input of data through a website. I have two time inputs (STARTTIME and TESTTIME) that are in HH:MM format. I need to display the time 15 minutes after STARTTIME (15MIN) and the number of minutes that have passed between STARTTIME AND TESTTIME (TIMEDIF).
The website provides the drag & drop form editor and has a field where I can add javascript to the form.
I've figured out how to take string inputs of "HH:MM" and output the values I need.
I am struggling with extracting the input from the two time fields (STARTTIME and TESTTIME) and writing to the 15MIN and TIMEDIF fields.
For returning the input from the form, I've tried using:
var atime = $("#" + STARTTIME + "input");
var ttime = $("#"+ TESTTIME + "input");
//-or-
var atime = $("div[id=STARTTIME] input");
var ttime = $("div[id=TESTTIME] input");
//and for setting the 15MIN and TIMEDIF variables
$("div[id=15MIN] input").val(tqtime);
$("div[id=TIMEDIF] input").val(difftime);
//tqtime and difftime are in "HH:MM" and number format, respectively and are calculated from atime and ttime.
I have tested the output of the code from atime and ttime defined as "HH:MM" strings to tqtime and difftime, which has been successful.
However, all variables are undefined when used with the form, leading me to believe that I'm not returning the input correctly.
When you call $("someselector"), what you get is a jQuery element. This is more than just the value of the input, and thus you must actually call a function to get that value. With jQuery, you use the .val() method to achieve this. Assume that "#" + STARTTIME + input" and "#" + TESTTIME + "input" are ids of input elements, getting the values would look like this:
var atime = $("#" + STARTTIME + "input").val();
var ttime = $("#" + TESTTIME + "input").val();
Currently, I am pulling in a json feed from our calendar. It brings back the date in the yyyy/mm/dd format... I know I can overwrite this format by using javascript but how would I do this? I need the output to only be the "dd" not the month nor the year.
I would also like single digit days to show up as i.e. "1","2","3","4" and of course dbl digits to show up as usual "10", "11", "12", etc. Any ideas on how I could achieve this reformatting of the date via javascript/jquery?
You can use a Date object
var theDate = new Date(dateString);
var theDay = parseInt(theDate.getDate(), 10);
Alternatively, if you don't want to use the object and can expect the same string back each time:
var theDay = parseInt(dateString.split('/')[2], 10);
This code should do it . . .
var jsonDate = <...reference to the JSON date value...>;
var dayValue = jsonDate.split("/")[2].replace(/0(.)/, "$1");
You've already got a string value, so might as well just manipulate it as a string.
jsonDate.split("/")[2] splits up the full date and then takes the third item from the resulting array (i.e., the day value)
.replace(/^0(.)$/, "$1") will trim off the "0", if it finds it in the first position of the "day" string
Then you just use dayValue wherever you need to use it. :)
UPDATE:
Based on the comments below, try using this as your code:
var listingEl = $('<div class="eventListings" title="' + item.event.title + '" />');
var dateEl = $('<div class="mdate">' + dayValue + '</div>');
var linkEl = $('<a href="' + item.event.localist_url + '" />');
var titleEl = $('<div class="mcTitle">' + item.event.title + '</div>');
linkEl.append(titleEl);
listingEl.append(dateEl);
listingEl.append(linkEl);
$('#localistTitle').append(listingEl);
UPDATE 2:
There was something not working in your code (I think the main issues was how you were using .appendTo()). I split it out into a multi-step process and used .append() instead. It worked correctly when I tested it locally.
Say I have this mockup-code:
button.click(function(){generateForm();}
function generateForm(){
div.append(<input type='text' id='x'>);
}
I will need the ID in order to access the element individually.
What is the best way to avoid having ID-conflicts in a scenario like this ?
Its better to use class instead. But if you are still willing to use id, you may consider using a counter like this:
var idCounter = 1;
function generateForm(){
div.append("<input type='text' id='x-" + (idCounter++) + "'>");
}
If you absolutely need to, you could use the current timestamp for an id.
That obviously produces no duplicate IDs unless you call the function more than once per millisecond or your users get stuck in timeloops often.
function generateForm(){
d = new Date();
div.append('<input type="text" id="unique-id-' + d.getTime() + '" >);
}
Edit: Note the unique-id- prefix, for id shouldn't be numeric only.
If you don't want to keep track of an external counter, try:
function makeAVeryRandomId () {
var d = new Date(),
a = ["0","1","2","3","4","5","6","7","8","9"],
i = 10,
m = '';
while (i--) {
m += a[Math.floor(Math.random() * a.length)];
};
return d.getTime() + m;
};
Bear in mind that IDs shouldn't start with a number, so prefix the random number with a letter (or two).
If I have a date like 8/9/2010 in a textbox, how can I easiest set a variable to the value 201098?
Thanks in advance.
var date = "8/9/2010";
var result = date.split('/').reverse().join('');
EXAMPLE: http://jsfiddle.net/hX357/
To add leading zeros to the month and day (when needed) you could do this:
var date = "8/9/2010";
var result = date.split('/');
for( var i = 2; i--; )
result[i] = ("0" + result[i]).slice(-2);
result = result.reverse().join('');
EXAMPLE: http://jsfiddle.net/hX357/2/
I would recommend using Datejs to process your dates.
You can do something like
date.toString("yyyyMMdd");
to get the date in the format you want
Using regex:
"8/9/2010".replace(/([0-9]+)\/([0-9]+)\/([0-9]+)/,"$3$2$1")
Do a split on '/', take the last element and make it the first of a new string, the middle element becomes the middle element of the new string, and the first element becomes the last element of a new string.
It would be like this:
myString = document.getElementById('date_textbox').value;
var mySplitResult = myString.split("\");
var newString = mySplitResult[2] + mySplitResult[1] + mySplitResult[0];
This is basically the idea I think you are going for.
-Brian J. Stinar-
Dang, it looks like I was beaten to the punch...
Or you can use the built-in JavaScript Date class:
function processDate(dStr) {
var d = new Date(dStr);
return d.getFullYear() + (d.getMonth() + 1) + d.getDate();
}
processDate("8/9/2010");
Easiest to manage and debug, certainly.
I have this as my date: 1212009 so this should be like 12/1/2009 but I am stuck this as an id field and id fields cannot have dashes in there names.
Now can java-script take this number and re add the slashed in for me or how would I go about doing this?
Thanks
You should have two-digit numbers for the month and day, since "1212009" is ambiguous, could be interpreted as "1/21/2009" or "12/1/2009".
If you add the leading zeros, you know that there will be always 8 digits, so you can do something like this:
var str = "12012009"
var result = str.replace(/(\d{2})(\d{2})(\d{4})/, "$1/$2/$3");
// 12/01/2009
Or
var result = str.match(/(\d{2})(\d{2})(\d{4})/).slice(1).join('/');
// 12/01/2009
Well without leading zeros, it's not possible to make a reliable conversion. It's impossible to know if 1232009 is 1/23/2009 or 12/3/2009 without leading zeros. Also, your example number could be interpreted as 1/21/2009 too.
All you need to do is pass the string into the new date constructor.
Here is a good javascript resource for you to look at.
http://www.javascriptkit.com/jsref/date.shtml
Assuming that you add the leading zeroes to remove the ambiguity, you can format the date like so:
dateString = String(id).match(/(\d{2})(\d{2})(\d{4})/).slice(1).join('/')
Maybe this will help you to get rid of the six or seven numbers long date (most important part is the first part):
var sDate = "1212009";
if(sDate.length == 7){
sDate = sDate.substr(0,2) + "0" + sDate.substr(2);
}
else if(sDate.length == 6){
sDate = "0" + sDate.substr(0,1) + "0" + sDate.substr(1);
}
// This part can be done with Regular Expressions, as shown in other comments
var month = parseInt(sDate.substring(0,2));
var day = parseInt(sDate.substring(2,4));
var year = parseInt(sDate.substring(4));
alert(day + "/" + month + "/" year);
// Will alert 12/1/2009
However,
1232009 will always be 01/23/2009, not 12/03/2009
112009 changes to 1/1/2009
10102009 changes to 10/10/2009