jquery trim text value and format
I have some jquery which grabs an elements id and places it into a textbox
The i开发者_开发百科d of the textbox is automatically set so i can't change it.
I'm trying to trim the id and then format it so that it reads properly
Here's my HTML
<a id="day_2294_110_2011-6-2" class="weekday" href="javascript:;">Day</a>
<input type="text" id="therapydate" />
And my jQuery
$('.weekday').click(function() {
$('#therapydate').val($(this).attr('id'));
});
This puts the value of my textbox to day_2294_110_2011-6-2
but i'd like to remove this day_2294_110_
and just be left with 2011-6-2
and then format that as a date like this 2nd June 2011
or 02/06/2011
Is this possible?
Thanks
Try this(gives you the date in MM/DD/YYYY format):
var id = $('#therapydate').val($(this).attr('id'));
var requiredOP = id.replace(/.*_(\d+)-(\d+)-(\d+)$/, '$2/$3/$1');
Working example: http://jsfiddle.net/L42Lq/
In this case you could use the string.split() method to break it up into an array, in this case the array would contain 4 elements and the last element is the piece you want.
Something like:
var splitId = $(this).attr('id').split('_');
$('#therapydate').val(splitId[3]);
try something like this:
var date = new Date ("day_2294_110_2011-6-2".substring(13, 21)).toUTCString();
Well, you can get the date inside this id in many ways. You could try using regExp, split per '-' or even using substring function. After this, to format your date properly, you could try this: http://docs.jquery.com/UI/Datepicker/formatDate
You can split()
on an underscore and grab the last item in the array:
var id = $(this).attr('id'));
var parts = id.split('_');
var datePart = parts[parts.length-1];
You can alternatively get the last index of the underscore and then grab a substring of everything to the right of it:
var id = $(this).attr('id'));
var index = id.lastIndexOf('_') + 1;
var datePart = id.substr(index);
There's a lot of date formatting documentation out there. Just google around. For example: http://plugins.jquery.com/project/jquery-dateFormat
Use @Cybernate's solution.
$('.weekday').click(function() {
var date = $(this).attr('id');
$('#therapydate').val(date.slice(date.lastIndexOf("_")+1, date.length));
});
Try it here
精彩评论