What do I need to change in my code?
Each element with the class "date_entry" should have a different attribute set, but currently all elements with that class are getting the same attribute...
$("document").ready(function() {
$(".date_entry").each(function() {
if ($(".date_entry").attr("date", "")) {
var date = $(this).text();
var splitDate = date.split('/');
var year = splitDate[2];
var month = splitDate[0];
var day = splitDate[1];
var newAttr = year + month + day;
$(".date_entry").attr("date", newAttr);
}
});
});
Use the "this" variable:
$(function() {
$(".date_entry").each(function() {
var date = $(this).text();
var splitDate = date.split('/');
var year = splitDate[2];
var month = splitDate[0];
var day = splitDate[1];
var newAttr = year + month + day;
$(this).attr("date", newAttr);
});
});
You have to use $(this) instead of $(".date_entry") inside the function you are passing to each(). $(".date_entry") selects again all elements with that class.
Related
I am looking for help why this code is not working for all headings of column. This code works for fist time for any column but does not fire click event second time. why $(ColTh).click(function () is not being attached to all th in header ?
$("table.ui-datepicker-calendar > thead").find("th[scope='col']").each(function() {
var ColTh = $(this);
$(ColTh).click(function() {
var colIndex = $(ColTh).index();
var dateList = [];
$(ColTh).closest('table').find('tr').each(function() {
var dateTd = $(this).find('td:eq(' + colIndex + ')');
var month = $(dateTd).attr('data-month'); //.trigger('click');
var year = $(dateTd).attr('data-year');
var day = $(dateTd).children(0).text();
if (typeof month != 'undefined') {
var monthINT = parseInt(month.trim());
monthINT = monthINT + 1;
var newDate = monthINT + '-' + day.trim() + '-' + year.trim();
dateList.push(newDate);
}
});
$('#itemSchedulerCal').multiDatesPicker('addDates', dateList);
dateList = [];
});
});
I'm not sure about the rest of your code, but about your binding, you can do like this:
$("table.ui-datepicker-calendar").on("click", "th[scope='col']", function() {
var ColTh = $(this);
var colIndex = ColTh.index();
var dateList = [];
ColTh.closest('table').find('tr').each(function() {
var dateTd = $(this).find('td:eq(' + colIndex + ')');
var month = dateTd.attr('data-month'); //.trigger('click');
var year = dateTd.attr('data-year');
var day = dateTd.children(0).text();
if (typeof month != 'undefined') {
var monthINT = parseInt(month.trim());
monthINT = monthINT + 1;
var newDate = monthINT + '-' + day.trim() + '-' + year.trim();
dateList.push(newDate);
}
});
$('#itemSchedulerCal').multiDatesPicker('addDates', dateList);
dateList = [];
});
You are using to ColTh as $(ColTh), but ColTh is already a jQuery object since you are setting it with $(this). The same applies to dateTd.
i did following steps to achieve above
Step 1:
jQuery(document).ready(function () {
$.datepicker._updateDatepicker_original = $.datepicker._updateDatepicker;
$.datepicker._updateDatepicker = function (inst) {
$.datepicker._updateDatepicker_original(inst);
var afterShow = this._get(inst, 'afterShow');
if (afterShow) {
// trigger custom callback
afterShow.apply((inst.input ? inst.input[0] : null));
}
}
});
step 2:
$('#itemSchedulerCal').multiDatesPicker({
showWeek: true,
minDate: 0,
dateFormat: "m-d-yy",
dayNamesMin: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
defaultDate: defdate,
afterShow: function (inst)
{
BindClicks();
}
});
Step 3:
function BindClicks() {
// paste all above code
}
I have the following string:
bar
So I can pull the title as a string, but I want to replace the {m{month}m} with {m{August}m} and it needs to be flexible enough so I can also then again replace it with {m{September}m}
I currently have this:
var thetitle = $(this).attr('title');
var newtitle = thetitle.replace("{m{month}m}",months[currentmonth]);
And this replaces fine the 1st time, but then it strips out the entire value and replaces "{m{month}m}" with say "August", so when I need to replace it again I can't target it.
Any help would be appreciated.
G
Try to use
var changeMonth = (function(){
var previous = 'month' ;
return function(title,month){
var temp = previous;
previous = month
return title.replace('m{' + temp + '}m', month);
}
})();
This works for me. Try
var changeMonth = (function(){
var previous = 'month' ;
return function(title,month){
var temp = previous;
previous = month;
return title.replace('m{' + temp + '}m','m{'+ month + '}m');
}
})();
var input = $('input');
var a = $('a');
$('button').on('click', function(){
var month = input.val();
var newMonth = changeMonth($(a).attr('title'), month);
$(a).attr('title', newMonth);
console.log($(a).attr('title'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Your month here<input type='text'>
<button>Change</button>
var title = "blahblah?foo=1&month={m{August}m}";
var previousmonth = "August";
var previousmonthstr = "{m{" + previousmonth + "}m}";
var currentmonth = "September";
var currentmonthstr = "{m{" + currentmonth + "}m}";
var newtitle = title.replace(previousmonthstr, currentmonthstr);
// Your title is stored in newtitle
View live demo here
I would like to create a simple if / else statement with JS. That would check if a div element has changed, before populating JSON data fields / variables that pull from dynamically changed HTML.
I do not want to use the DOMSubtreeModified. As it's depreciated..
Below is the started logic, I have. But it looks like I'll have to scrap the DOMSubtreeModified out for a method that is not depreciating.
The question / problem is: How to re-write not using the above depreciated technique, and how to nest my data array, where it will only pull / populate based on first checking my if (condition) Cheers for any pointers.
var element = document.querySelector('.username'); // username div wrapper
//if {
element.addEventListener('DOMSubtreeModified', function() { // detect if div element changes
var date = new Date();
var month = date.getUTCMonth() + 1;
var day = date.getUTCDate();
var year = date.getUTCFullYear();
var time = date.toLocaleTimeString();
var formattedDate = month + '/' + day + '/' + year;
console.log(time); // 7:01:21 PM
console.log(formattedDate); // 3/15/2016
}, false);
// change something on element
setTimeout(function() {
element.dataset.username = 'bar';
}, 3000);
// json object with captured data fields
var NewUserSession = [{
currentusername: $('.username').text(),
referrer: document.referrer,
loggedintime: $(formattedDate),
}];
//}
//
//else {
//
//
//}
You can use MutationObserver and watch for data-username changes
var element = document.querySelector('.username'); // username div wrapper
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.attributeName = 'data-username') {
var date = new Date();
var month = date.getUTCMonth() + 1;
var day = date.getUTCDate();
var year = date.getUTCFullYear();
var time = date.toLocaleTimeString();
var formattedDate = month + '/' + day + '/' + year;
snippet.log(time); // 7:01:21 PM
snippet.log(formattedDate); // 3/15/2016
}
});
});
var config = {
attributes: true,
attributeFilter: ['data-username']
};
// pass in the target node, as well as the observer options
observer.observe(element, config);
// change something on element
setTimeout(function() {
element.dataset.username = 'bar';
}, 1000);
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<div class="username"></div>
thanks for taking the time reading this.
I have a code snippet that has already some functions inside. Now I want to run that script if a button was clicked. From what I've tested it seems like it's not possible to put the snippet with its functions into a parent function (, is it?).
Now I wonder, what is the best way to call the javascript code snippet?
I don't think that is important for this general question, but here's my script I want to call:
var $input = $( '.datepicker2' ).pickadate({
})
var picker = $input.pickadate('picker')
var plusDays = 1;
var currentSelection = picker.get();
var currentDay;
var currentMonth;
var currentYear;
var newDay;
strich = currentSelection.indexOf("-");
currentYear = currentSelection.substring(0, strich);
strich = currentSelection.indexOf("-");
currentMonth = currentSelection.substring(strich + 1);
strich = currentMonth.indexOf("-");
currentMonth = currentMonth.substring(0, strich);
strich = currentSelection.indexOf("-");
currentDay = currentSelection.substring(strich + 1);
strich = currentDay.indexOf("-");
currentDay = currentDay.substring(strich + 1);
newDay = parseInt(currentDay) + plusDays;
var $input = $( '.datepicker' ).pickadate({
})
var picker = $input.pickadate('picker')
var date = new Date()
picker.set('select', [currentYear, currentMonth - 1, newDay])
Here you are:
function snippet() {
var $input = $( '.datepicker2' ).pickadate({});
var picker = $input.pickadate('picker')
var plusDays = 1;
var currentSelection = picker.get();
var currentDay;
var currentMonth;
var currentYear;
var newDay;
strich = currentSelection.indexOf("-");
currentYear = currentSelection.substring(0, strich);
strich = currentSelection.indexOf("-");
currentMonth = currentSelection.substring(strich + 1);
strich = currentMonth.indexOf("-");
currentMonth = currentMonth.substring(0, strich);
strich = currentSelection.indexOf("-");
currentDay = currentSelection.substring(strich + 1);
strich = currentDay.indexOf("-");
currentDay = currentDay.substring(strich + 1);
newDay = parseInt(currentDay) + plusDays;
var $input = $( '.datepicker' ).pickadate({
})
var picker = $input.pickadate('picker')
var date = new Date()
picker.set('select', [currentYear, currentMonth - 1, newDay])
}
And you can call everywhere, everytime you need:
$(document).ready(function() {
//stuff
snippet() ;
});
If you have a function inside the function (like this)
function snippet() {
var $input = $( '.datepicker2' ).pickadate({});
var picker = $input.pickadate('picker')
var plusDays = 1;
var currentSelection = picker.get();
var currentDay;
this.anotherFunction = function() {
// some stuff
}
}
You can call it:
snippet.anotherFunction();
Good luck
I have this code that updates a calendar widget and input field, while validating the date. We want the user to be able to input any type of m-d-y format (m.d.y, m-d-y, and so on). The problem is the YUI calendar widget only accepts the m/d/y format. All others it returns as NaN. I have tried a couple ways to format the date, but can't get anything that seems to work. I would like to be able to do this with out a lot of overblown code. Does anyone have any suggestions as to the best approach here? Here is my code:
//CALENDAR --------------------------------------------------------------------------------
var initCal = function(calendarContainer){
if(YAHOO.env.getVersion("calendar")){
var txtDate = Dom.get("dateOfLoss");
var myDate = new Date();
var day = myDate.getDate();
var month = myDate.getMonth() +1;
var year = myDate.getFullYear() -1;
var newDate = month + "/" + day + "/" + year;
function handleSelect(type, args, obj){
var dates = args[0];
var date = dates[0];
var year = date[0], month = date[1], day = date[2];
txtDate.value = month + "/" + day + "/" + year;
aCal.hide();
}
function updateCal(){
if (!(txtDate.value.match(/((\d{2})|(\d))\/|\-((\d{2})|(\d))\/|\-((\d{4})|(\d{2}))/))) {
alert("Enter date in mm/dd/yy or mm/dd/yyyy format.");
}
else {
if (txtDate.value != "") {
aCal.select(txtDate.value);
var selectedDates = aCal.getSelectedDates();
if (selectedDates.length > 0) {
var firstDate = selectedDates[0];
aCal.cfg.setProperty("pagedate", (firstDate.getMonth() + 1) + "/" + firstDate.getFullYear());
aCal.render();
}
else {
alert("Date of Loss must be within the past year.");
}
}
}
}
var aCal = new YAHOO.widget.Calendar(null, calendarContainer, {
mindate: newDate,
maxdate: new Date(),
title: "Select Date",
close: true
});
aCal.selectEvent.subscribe(handleSelect, aCal, true);
aCal.render();
Event.addListener("update", "click", updateCal);
Event.addListener(txtDate, "change", function(e){
updateCal();
});
// Listener to show the 1-up Calendar when the button is clicked
// Hide Calendar if we click anywhere in the document other than the calendar
Event.on(document, "click", function(e){
var el = Event.getTarget(e);
if(Dom.hasClass(el, "calendarButton"))
aCal.show();
else if (Dom.hasClass(el, "link-close") || !Dom.isAncestor(calendarContainer, el))
aCal.hide();
});
}
else {
var successHandler = function() {
initCal(calendarContainer);
};
OURPLACE.loadComponent("calendar", successHandler);
}
};
Did you tried http://www.datejs.com/?
Maybe you can define some patterns and test agaist the input.
How can I convert string to datetime with format specification in JavaScript?
var updateCal = function(){
if (!(txtDate.value.match(/^(0?[1-9]|1[012])[- /.](0?[1-9]|[12][0-9]|3[01])[- /.]\d\d+$/))) {
return;
}
//else if ((txtDate.value.match(/^(0?[1-9]|1[012])[- .](0?[1-9]|[12][0-9]|3[01])[- .]\d\d+$/))) {
//}
else {
var changedDate = txtDate.value;
changedDate = changedDate.replace(/[. -]/g, "/");
txtDate.value = changedDate;
badClaimDate = claimDateWithinPastYear();
aCal.select(changedDate);
I used a RegEx to determine which, if any, delimiters needed to be replaced and simply used .replace.