i have a partial view that itself is inside a partial view. The content inside the inner most partial view can be rendered multiple times. i have a javascript code that is significant only for the innermost view. SO what happens is when the content is rendered more than once the javascript code is added twice and event are called twice. e.g
var isDccmAndReady = '#isDccmAndReady';
$(document).ready(function() {
$(function() {
$("input[name='ReportDate']").change(function() {
if (isDccmAndReady) {
var d = new Date();
var currentDate = (d.getMonth() + 1) + "/" + +d.getDate() + "/" + d.getFullYear();
var dateSelected = $(this).val();
if (new Date(dateSelected) > new Date(currentDate)) {
var answer = confirm("The contract has been already reported, are you sure you wish to continue?");
if (answer) {
return true;
} else {
$(this).val('#Model.OriginalReportDate.Value.ToShortDateString()');
return false;
}
}
}
return false;
});
});
Now if the textbox is embedded twice onchange event is called two times when something changes in one of the textbox. how to circumvent this issue?
I'm not sure about what you want, if you want a function to run only exactly once, you can use underscore "once" function:
var newfunction = _.once(yourfunction);
newfunction();
newfunction();
if your purpose is to prevent the event handler to add more than once in an element, you can first unbind the event and then bind it again like:
$("#someselector").unbind("change").change(function(){
})
Finally got it working. i added the following javascript in the partial view where the innermost partial is called so that javascript s registered in the dom once.i also added couple of data attributes in the text box whose value i needed in the javascript
$(document).ready(function () {
$(function () {
$("input[name='ReportDate']").change(function () {
if ($(this).attr('data-isDccmAndReady')) {
var d = new Date();
var currentDate = (d.getMonth() + 1) + "/" + +d.getDate() + "/" + d.getFullYear();
var dateSelected = $(this).val();
if (new Date(dateSelected) > new Date(currentDate)) {
var answer = confirm("The contract has been already reported, are you sure you wish to continue?");
if (answer) {
return true;
} else {
$(this).val($(this).attr('data-originalReportDateVal'));
return false;
}
}
}
return false;
});
});
});
Related
I'm using this jQuery script to show search results. Everything works fine, but when search results have more than one page and I'm browsing pages via paging then every page loading is gradually getting slower. Usually first cca 10 pages loads I get quickly, but next are getting avoiding loading delay. Whole website get frozen for a little while (also loader image), but browser is not yet. What should be the problem?
function editResults(def) {
$('.searchResults').html('<p class=\'loader\'><img src=\'images/loader.gif\' /></p>');
var url = def;
var url = url + "&categories=";
// Parse Categories
$('input[name=chCat[]]').each(function() {
if (this.checked == true) {
url = url + this.value + ",";
}
});
url = url + "&sizes=";
// Parse Sizes
$('input[name=chSize[]]').each(function() {
if (this.checked == true) {
url = url + this.value + ",";
}
});
url = url + "&prices=";
// Parse Prices
$('input[name=chPrice[]]').each(function() {
if (this.checked == true) {
url = url + this.value + ",";
}
});
$('.searchResults').load('results.php'+url);
$('.pageLinks').live("click", function() {
var page = this.title;
editResults("?page="+page);
});
}
$(document).ready(function(){
editResults("?page=1");
// Check All Categories
$('input[name=chCat[0]]').click(function() {
check_status = $('input[name=chCat[0]]').attr("checked");
$('input[name=chCat[]]').each(function() {
this.checked = check_status;
});
});
// Check All Sizes
$('input[name=chSize[0]]').click(function() {
check_status = $('input[name=chSize[0]]').attr("checked");
$('input[name=chSize[]]').each(function() {
this.checked = check_status;
});
});
// Edit Results
$('.checkbox').change(function() {
editResults("?page=1");
});
// Change Type
$(".sort").change(function() {
editResults("?page=1&sort="+$(this).val());
});
});
$('.pageLinks').live("click", function() {
var page = this.title;
editResults("?page="+page);
});
just a wild guess but... wouldn't this piece of code add a new event handler to the click event instead reaplacing the old one with a new one? causing the click to call all the once registered handlers.
you should make the event binding just once
var global_var = '1';
function editResults(def) {
// all your code
global_var = 2; // what ever page goes next
};
$(document).ready(function() {
// all your code ...
$('.pageLinks').live("click", function() {
var page = global_var;
editResults("?page="+page);
});
});
Hi guys this might be a really stupid error but im using jquery to add a formset to a page it also does other things such as updating the number of forms but that does not seem to be a issue.
http://jsfiddle.net/b5Y8f/
$(document).ready(function () {
function updateElementIndex(el, prefix, ndx) {
var id_regex = new RegExp('(' + prefix + '_set-\\d+-)');
var replacement = prefix + '_set-' + ndx + '-';
if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
if (el.id) el.id = el.id.replace(id_regex, replacement);
if (el.name) el.name = el.name.replace(id_regex, replacement);
}
function changeDeleteForms(el, prefix, formid) {
var idstring = 'id_' + prefix + '_set-' + formid + '-DELETE';
//$('<input>').attr({type: 'hidden', id: 'id_' + idstring, name: idstring}).appendTo('.command-delete');
$('#' + idstring).prop('checked', true);
}
function deleteForm(btn, prefix) {
var formCount = parseInt($('#id_' + prefix + '_set-TOTAL_FORMS').val());
if (formCount > 1) {
// Delete the item/form
$(btn).parents('.command').hide();
$(btn).parents('.command').attr('class', 'command-delete');
var dc = $(".command-delete");
$(dc).children().children().children().each(function () {
var formid = this.id.match(/\d+/g);
changeDeleteForms(this, prefix, formid);
//$(this).val("");
});
var forms = $('.command'); // Get all the forms
var formsdelete = $('.command-delete'); // Get all the forms
var fl = parseInt(forms.length);
var fdl = parseInt(formsdelete.length);
var finalcount = fl + fdl
// Update the total number of forms (1 less than before)
//$('#id_' + prefix + '_set-TOTAL_FORMS').val(forms.length);
var i = 0;
} // End if
else {
alert("Please enter atleast 1 command for this item.");
}
return false;
}
function addForm(btn, prefix) {
var formCount = parseInt($('#id_' + prefix + '_set-TOTAL_FORMS').val());
var maxCount = parseInt($('#id_' + prefix + '_set-MAX_NUM_FORMS').val());
var forms = parseInt($('.command-delete').length); // Get all the forms
var newcount = formCount + forms;
// You can only submit a maximum of 10 todo items
if (newcount < maxCount) {
// Clone a form (without event handlers) from the first form
var row = $(".command:first").clone(false).get(0);
// Insert it after the last form
$(row).removeAttr('id').hide().insertAfter(".command:last").slideDown(300);
// Remove the bits we don't want in the new row/form
// e.g. error messages
$(".errorlist", row).remove();
$(row).children().removeClass("error");
// Relabel or rename all the relevant bits
$(row).children().children().children().children().each(function () {
updateElementIndex(this, prefix, newcount);
$(this).val("");
});
// Add an event handler for the delete item/form link
$(row).find(".delete").click(function () {
return deleteForm(this, prefix);
});
// Update the total form count
$("#id_" + prefix + "_set-TOTAL_FORMS").val(newcount + 1);
} // End if
else {
alert("Sorry, you can only enter a maximum of 1000 items.");
}
return false;
}
// Register the click event handlers
$("#add").click(function () {
return addForm(this, "itemcommands");
});
$(".delete").click(function () {
return deleteForm(this, "itemcommands");
});
$('.command input:checkbox').hide();
});
If you go to the link above you can see the code works perfectly fine it update the form count and add the new form with the new number in the id and everything however in production when you click the add command button for the first 3 times it does not show however the code has been enter into the page and the form is technically there but not shown.
on the fourth time you press the button it works and the row has been added after the last ('.command') in the element.
What could be causing it to work on JSFiddle but not on production?
-------------------UPDATE--------------------------
It seems if i remove the overflow hidden from the 3 that dont show when you press the button the first 3 times it will show them in the correct place.
Why would overflow no be removed from the first 3 form rows but the rest after fine?
----------------------UPDATE--------------------------
Think i have found the issue and its nothing to do with the JQUERY at all it seems to be bootstraps responsive layout hiding the forms i think if i add them specifically to their own rows i can fix this.
Thanks for the help though guys.
I don't see a src="*jQuery source*" in your file. Since JSFiddle already adds the source to the file, you may have forgotten to put it in.
I using the FullCalendar and i would like display the count of events per day in all views for each days.
Example :
<div class="fc-day-number">1</div>
Change to :
<div class="fc-day-count">X</div>
<div class="fc-day-number">1</div>
Please find a screenshoot as example:
link
Thanks in advance
I hope this helps someone but don't know if it's the exact answer you're looking for.
To get the number of events that occur on a day you can use the following code:
$('#calendar').fullCalendar( 'clientEvents', function(eventObj){
if (eventObj.start.isSame('2014-11-21')) {
return true;
} else {
return false;
}
}).length;
As per fullcalendar documentation you can search for events with a filter function clientEvents.
The if statement in the function compares dates using moment.js which is included in fullcalendar 2.0
Sample in Month View EventsPerDay variable gives count
eventRender: function (event, element, view) {
$(element).each(function () { $(this).addClass('dateClass-' + event.start.getDate().toString()); $(this).attr('date-num', event.start.getDate().toString()); });
if (view.name == "month") {
// $('.shifts,.tasks,.shiftOut,.shiftIn').hide();
var CellDates = [];
var EventDates = [];
var EventCount = 0, i = 0;
$('.fc-view-month').find('.fc-day-number').each(function () {
CellDates[i] = $(this).text();
// alert( $(this).text());
i++;
});
for (j = 0; j < CellDates.length; j++) {
EventsPerDay = $(".fc-view-month>div>.dateClass-" + CellDates[j]).length;}}
I added a line to fullcalendar.js in the method named
function fetchEventSource(source, fetchID):
function fetchEventSource(source, fetchID) {
_fetchEventSource(source, function(events) {
if (fetchID == currentFetchID) {
if (events) {
if (options.eventDataTransform) {
events = $.map(events, options.eventDataTransform);
}
if (source.eventDataTransform) {
events = $.map(events, source.eventDataTransform);
}
// TODO: this technique is not ideal for static array event sources.
// For arrays, we'll want to process all events right in the beginning, then never again.
for (var i=0; i<events.length; i++) {
events[i].source = source;
normalizeEvent(events[i]);
}
cache = cache.concat(events);
}
pendingSourceCnt--;
if (!pendingSourceCnt) {
reportEvents(cache);
}
}
// add this next line here to dump the running count
$("#someElement").html("There are " + cache.length + " events scheduled for this view");
});
}
This has the net effect of leveraging what fullcalendar is already doing. You can then save yourself the extra network call on the database.
I use unitsview and weekview in scheduler.
I need to pass unitID(key) and date to another function, when I click header of classname: dhx_scale_bar.
I tried this code:
CODE: SELECT ALL
function showTitle(a) {
alert(a);
debugger;
var mode = scheduler.getState().mode;
var myDate = scheduler.getState().date;
alert(myDate);
});
if (mode == "units")
{
var hh= scheduler.getState().date;
alert(hh);
alert(mode);
}
else if (mode == "week" || mode=="decade") {
var a = document.getElementById('resourcename');
var cid = a.options[a.selectedIndex].value;
//here I get the unitId as i use list to filter_week.
var n = scheduler.getState().date;
alert(n);
// I get the same date(today's date) whenever i tried to click on any column in weekview or decade view
}
}
I attached showTitle(a) function in the main dhtlmxscheduler.js as I don't find any documentation to attach events on header. Please help.
You can use getActionData API
var unit = scheduler.getActionData(e).section;
where e - native html click event object
I'm unable to figure out where a syntax logical error resides in the script furthest below. Essentially what it does is it alerts people that they must wait 1.5 seconds before they can answer a radio-button type question and automatically move on to the next page. No alert if they spend more than 1.5 seconds.
This script was written for only one click event, but I need it to work for two nested events, where clicking on a radio button option automatically triggers the "next" button to move on to the next page. For example if you take out the following event (and its end brackets), it works well:
$("[class*=bfasg] .radio").click(function(){
I've checked the syntax at Esprima to make sure the brackets are correct, so the problem lies elsewhere.
$(document).ready(function() {
minTime(1.5);
function minTime(minTime) {
var startTime = new Date();
$("[class*=bfasg] .radio").click(function(){$("#movenextbtn").click(function(){
var endTime = new Date();
if((endTime - startTime)/1000 <= minTime) {
alert('You must spend at least '+minTime+' seconds on the question.');
return false;
}
else {
return true;
}
});
});
}
});
Any experts out there who can detect the problem?
(See answer to updated question below)
It's not a syntax error. It's a logic error.
It becomes slightly clearer if you format the code consistently:
$(document).ready(function () {
minTime(1.5);
function minTime(minTime) {
var startTime = new Date();
// Hooking up a click handler
$("[class*=bfasg] .radio").click(function () {
// This code doesn't run until/unless someone clicks
// one of the `[class*=bfasg] .radio` elements.
$("#movenextbtn").click(function () {
var endTime = new Date();
if ((endTime - startTime) / 1000 <= minTime) {
alert('You must spend at least ' + minTime + ' seconds on the question.');
return false;
} else {
return true;
}
});
});
}
});
What you've done there is said "When someone clicks a [class*=bfasg] .radio element, hook up an event handler on the #movenextbtn element."
You probably don't want to wait to hook up the event until someone clicks on a radio button. If your goal is to hook up the click event on both sets of elements, combine them in the same selector as you would in CSS:
$(document).ready(function () {
minTime(1.5);
function minTime(minTime) {
var startTime = new Date();
$("[class*=bfasg] .radio, #movenextbtn").click(function () {
var endTime = new Date();
if ((endTime - startTime) / 1000 <= minTime) {
alert('You must spend at least ' + minTime + ' seconds on the question.');
return false;
}
});
}
});
(By the way, returning true from a jQuery event handler has no meaning, so I've removed it above.)
Below you've commented:
What happens is that I want clicking the radio button to automatically trigger the "Next" button for going to the next page since I have one question per page.
That doesn't fundamentally change things. You haven't shown what the button does to move to the next page, but you'd just put that code in the one click handler above. E.g., you still hook click on both the radio buttons and the button, and you still handle that event using common code. E.g.:
$(document).ready(function () {
minTime(1.5);
function minTime(minTime) {
var startTime = new Date();
$("[class*=bfasg] .radio, #movenextbtn").click(function () {
var endTime = new Date();
if ((endTime - startTime) / 1000 <= minTime) {
alert('You must spend at least ' + minTime + ' seconds on the question.');
return false;
} else {
// ****Move to next page here****
}
});
}
});
Alternately, you could have the radio button click trigger a click event on the button, like this:
$(document).ready(function () {
minTime(1.5);
function minTime(minTime) {
var startTime = new Date();
// Hook up `click` on the radio buttons
$("[class*=bfasg] .radio").click(function () {
// Respond to click by firing click on the #movenextbtn
$("#movenextbtn").click();
});
// Hook up `click` on the #movenextbtn
$("#movenextbtn").click(function () {
var endTime = new Date();
if ((endTime - startTime) / 1000 <= minTime) {
alert('You must spend at least ' + minTime + ' seconds on the question.');
return false;
}
});
}
});
I'm not a huge fan of firing synthetic events like that when you could use common logic, but it's an option.
function callMe() {
// Do Something
}
$(document).ready(function() {
callMe();
});
DECLARE FUNCTION outside of ready(), but then define FUNCTION inside of ready().it's better to define them outside of document ready. And, if you need to, place the implementation of the method within the document ready.