Why 'click' doesn't work event on body in this case - events

I've tried to make event deledation, set "click" event on body. Event works on button. But why it doesn't work on body?
window.onload = function(){
var bodyN = document.body,
bodyS = bodyN.style
bodyS.transition = "all 0s";
bodyS.backgroundColor = localStorage.getItem("bgc")
bodyN.addEventListener("click", function(e){
console.log(e.target); // why doesn't work this when I click on body?
if (e.target.tagName == "BUTTON") {
console.log(e);
bodyS.transition = "";
bodyS.backgroundColor = e.target.id;
localStorage.setItem("bgc", e.target.id);
}
});
};
the same via jQuery:
$(document).ready(function(){
$("body").css("transition", "all 0s" );
$("body").css("backgroundColor", localStorage.getItem("bgc"));
$("body").on("click", "button", function(e){
console.log(e);
$("body").css("transition", "" );
$("body").css("backgroundColor", e.target.id);
localStorage.setItem("bgc", e.target.id);
})
});

With jQuery, I used "click" instead of "on". Here's an example:
$("body").click(function(e){
console.log(e);
if(e.target.id == "button"){
alert('button');
}
else{
alert('body');
}
});
https://jsfiddle.net/aumayk6s/
Hope it helps you!

Related

.click function ask me twice for confirmation

I have this issue, maybe you guys can help me fix it.
Botton Delete:
<button type="button" class="del-trade">Delete</button>
Ajax code:
$(function(){
$("#modaledittrade").on("show.bs.modal", function (e) {
$('.del-trade').click(function(){
var id = $(e.relatedTarget).attr( "data-id" );
if( confirm( "Are you sure?") )
{
$.post( "actions.php?a=del-trade", { "id" : id },function(d){
if( d.type!="ok" )
{
alert( d.msg );
return;
}
$( "tr#" + id ).remove();
resetForms( e.currentTarget );
$( "#modaledittrade").modal('hide');
},"json");
}
});
});
});
The code is give me loop twice... I mean ask me for function confirm() twice.
Video demo: http://sc.sny.pt/sJH6
On what I see, I think reason is because you create multiple instance of onclick event:
first time you delete (when modal is shown) create onclick event and the
second time that create a second event.
This should work :
$(function(){
/*$("#modaledittrade").on("show.bs.modal", function (e) {
}); */
$('.del-trade').click(function(){
var id = $(e.relatedTarget).attr( "data-id" );
if( confirm( "Are you sure?") )
{
$.post( "actions.php?a=del-trade", { "id" : id },function(d){
if( d.type!="ok" )
{
alert( d.msg );
return;
}
$( "tr#" + id ).remove();
resetForms( e.currentTarget );
$( "#modaledittrade").modal('hide');
},"json");
}
});
});
You can pull the click event out, and this will still work as expected, using on:
$(document).on("click", '.del-trade', function(e){
var id = $(e.relatedTarget).attr( "data-id" ); // can still get ID same way
if( confirm( "Are you sure?") )
{
$.post( "actions.php?a=del-trade", { "id" : id },function(d){
if( d.type!="ok" )
{
alert( d.msg );
return;
}
$( "tr#" + id ).remove();
resetForms( e.currentTarget );
$( "#modaledittrade").modal('hide');
},"json");
}
});
EDIT: Or, when the modal is hidden, turn off the delete click action:
$("#modaledittrade").on("hide.bs.modal", function (e) {
$('.del-trade').off("click");
});
$("#modaledittrade").on("show.bs.modal", function (e) {
$('.del-trade').on("click", function(e) { .. });
});

Grid columns shrink in Kendo grid after excel export

I am new to Kendo-UI and Web-Engineering and I am facing a problem which I haven't solved after investing hours of time.
I have a grid with 8 columns, and a Excel toolbar button. When I fire the excelExport event, i show 2 more hidden columns to include their data in the report, and after that I hide them again.
My Problem is that my columns shrink for the hidden columns when they are shown, yet dont expand their width afterwards when they're hidden again.
Here's my script for the excelExport event:
<script type="text/javascript">
var exportFlag = false;
$(window).load(function() {
$("#pr-grid").data("kendoGrid").bind("excelExport",function(e) {
if (!exportFlag) {
e.sender.showColumn("CallOff");
e.sender.showColumn("LastChange");
e.preventDefault();
exportFlag = true;
setTimeout(function() {
e.sender.saveAsExcel();
});
} else {
e.sender.hideColumn("CallOff");
e.sender.hideColumn("LastChange");
exportFlag = false;
}
});
});
</script>
I'd appreciate any help.
Regards Paparis
$('#pr-grid table').width('100%');
<script type="text/javascript">
var exportFlag = false;
function excelExport(e) {
if (!exportFlag) {
e.sender.showColumn("CallOff");
e.sender.showColumn("LastChange");
e.preventDefault();
exportFlag = true;
setTimeout(function() {
e.sender.saveAsExcel();
});
} else {
e.sender.hideColumn("CallOff");
e.sender.hideColumn("LastChange");
exportFlag = false;
$('#grid table').width('100%');
}
}
</script>

jquery datatables fnAddData from dialog form ajax not working

I have a datatable defined at document ready as follows
$(document).ready(function() {
var oTable = $('#systemgoals').dataTable({});
I have a dialog with form and a button with the following function
buttons: {
"Add System Goal": function() {
var formfilled = true;
$("form#add_systemgoal :text, form#add_systemgoal :file, form#add_systemgoal :checkbox, form#add_systemgoal select, form#add_systemgoal textarea").each(function() {
if($(this).val() === "")
formfilled = false;
});
if(formfilled === true){
$('form#add_systemgoal .error').remove();
var formdata = $('form#add_systemgoal').serialize();
$.ajaxSetup({async: false});
$.ajax({
type: "POST",
url: '/admin/systemgoals/systemgoalupdate?format=html',
data: formdata,
success: function (data) {
var obj = $.parseJSON(data);
if(obj.success){
$(oTable).dataTable().fnAddData( [
obj.inserted.goal_id,
obj.inserted.value,
obj.inserted.status,
obj.inserted.points_per_action,
obj.inserted.created,
obj.inserted.due,
obj.inserted.expires ]);
}
}
});
}
the ajax is fine the form posts the correct values respond but the fnAddData returns error
ReferenceError: oTable is not defined
Any advice appreciated
thank you
You didn't set your oTable as a global variable that why oTable on your dialog is not define, if you want to define it on your script do something like:
var oTable;
$(document).ready(function() {
oTable = $('#systemgoals').dataTable({});
And on your dialog
oTable.fnAddData( [
obj.inserted.goal_id,
obj.inserted.value,
obj.inserted.status,
obj.inserted.points_per_action,
obj.inserted.created,
obj.inserted.due,
obj.inserted.expires ]);
}
or just simply do
var oTable = $('#systemgoals').dataTable().fnAddData...
Best Regards

Using hashchange to load dynamic pages not working with secondary nav

Any ideas on why this won't work. I am using the tutorial from CSS-Tricks using AJAX to load pages dynamically. This works fine up until I introduced a secondary navigation on some pages which caused pages to load normally.
This is the code I am using. I am using classes to style the different nav areas.
$(function() {
var newHash = "",
$mainContent = $("#main-content"),
$pageWrap = $("#page-wrap"),
baseHeight = 0,
$el;
$pageWrap.height($pageWrap.height());
baseHeight = $pageWrap.height() - $mainContent.height();
$("nav").delegate("a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
$(window).bind('hashchange', function(){
newHash = window.location.hash.substring(1);
if (newHash) {
$mainContent
.find("#guts")
.fadeOut(200, function() {
$mainContent.hide().load(newHash + " #guts", function() {
$mainContent.fadeIn(200, function() {
$pageWrap.animate({
height: baseHeight + $mainContent.height() + "px"
});
});
$("nav a").removeClass("current");
$("nav a[href="+newHash+"]").addClass("current");
});
});
};
});
$(window).trigger('hashchange');
});
Website: http://darynjohnson.com/Medical%20Futures/about.php
Those new created links do not have any events bound to them because u set delagate function on the the object which is not changed. New added objects with the same tag ("nav" here) won't get delagation.
Use:
$('#page').delegate("nav a", "click", function() {
window.location.hash = $(this).attr("href");
return false;
});
Also I recommend you to upgrade jQuery to the newest version and replace delegate() with on()

jQuery UI Dialog Validation

I know this is a common problem. I've been looking at the various solutions proposed on this site and elsewhere but cannot hit upon something that works in my situation.
Here is my script:
$(function () {
$('a.editPersonLink').live("click", function (event) {
loadDialog(this, event, '#personList');
$.validator.unobtrusive.parse('#editPersonContainer');
});
$(".deleteButton").live("click", function(e) {
e.preventDefault();
var $btn = $(this);
var $msg = $(this).attr("title");
confirmDelete($msg,
function() {
deleteRow($btn, $target);
});
});
});
function loadDialog(tag, event, target) {
event.preventDefault();
var $loading = $('<img src="../../Content/images/ajaxLoading.gif" alt="loading" class="ui-loading-icon">');
var $url = $(tag).attr('href');
var $title = $(tag).attr('title');
var $dialog = $('<div></div>');
$dialog.empty();
$dialog
.append($loading)
.load($url)
.dialog({
autoOpen: false
,title: $title
,width: 800
,modal: true
,minHeight: 200
,show: 'slide'
,hide: 'clip'
});
$dialog.dialog( "option", "buttons", {
"Save": function () {
var dlg = $(this);
$.ajax({
url: $url,
type: 'POST',
data: $("#formData").serialize(),
success: function (response) {
$(target).html(response);
dlg.dialog('close');
dlg.empty();
$("#ajaxResult").hide().html('Record saved').fadeIn(300, function () {
var e = this;
setTimeout(function () { $(e).fadeOut(400); }, 2500);
});
},
error: function (xhr) {
if (xhr.status == 400)
dlg.html(xhr.responseText, xhr.status); /* display validation errors in edit dialog */
else
displayError(xhr.responseText, xhr.status); /* display other errors in separate dialog */
}
});
},
"Cancel": function() {
$(this).dialog("close");
$(this).empty();
}
});
$dialog.dialog('open');
};
Right up near the top I am trying to cause the form to recognise the validation from the partial view on the dialog via the statement:
$.validator.unobtrusive.parse('#editPersonContainer');
editPersonContainer is the name of the div containing the data in the partial view loaded into the dialog.
The bottom line is that the validation is not recognised. Am I making the call to validator.unobtrusive.parse in the wrong place, or am I missing something else here?
I ended up changing my script to use the techniques described here
Validation now works on my jQuery UI dialogs.
Hi I came up to your question as I was looking for the same.
I include this before the ajax call to validate on client side:
if (ModelState.IsValid) {}
I make an article with the full project on
Validation client/Server JqueryUI Dialog

Resources