focusin event using on not firing - javascript

I am attempting to perform some action on the foucsin of the textbox. However, for some reason the event never fires.
$(".ddlAddListinTo li").click(function () {
var urlstring = "../ActionTypes";
$.post(urlstring, function (data) {
$(window.open(urlstring, 'Contacts', 'width=750, height=400')).load(function (e) {
// Here "this" will be the pop up window.
$(this.document).find('#txtAutocompleteContact').on({
'focusin': function (event) {
alert('You are inside the Contact text box of the Contacts Popup');
}
});
});
});
});

When doing it that way, you generally have to find the body or use contents() to access the contents, as in
$(this.document).contents().find('#txtAutocompleteContact')
but in this case using a little plain javascript seems more appropriate :
$(".ddlAddListinTo li").on('click', function () {
var urlstring = "../ActionTypes";
$.post(urlstring, function (data) {
var wind = window.open(urlstring, 'Contacts', 'width=750, height=400');
wind.onload = function() {
var elem = this.document.getElementById('txtAutocompleteContact');
$(elem).on('focus', function() {
alert('You are inside the Contact text box of the Contacts Popup');
});
}
});
});

Related

Button click wont trigger function

I'm having trouble triggering a function. I have the following code:
var dnfmomd;
dnfmomd = new function () {
//function content
}
$("#launch_button").on("click", dnfmomd.init);
Have you tried this?
var dnfmomd = function () {
//function content
}
$("#launch_button").on("click", dnfmomd());
I would recommend doing it this way
var dnfmomd = function() {
//function content
}
$("#launch_button").on("click", function() {
dnfmomd();
});

Jquery on click event is not working when ajax call is running at loop

I have two ajax functions that one is recursively working at loop and other is working when click event invoked. I tested both of the functions that are able to work properly. But when i start recursive function button event is not invoked.
Function that works on click event GET Content from ActionResult (MVC)
function UpdateRequests(url, state, id, cell)
{
$.ajax({
type: "GET",
url: url + id,
success: function (result) {
if (result == "OK")
{
cell.fadeOut("normal", function () {
$(this).html(state);
}).fadeIn();
}
else if(result == "DELETE" || result == "CANCEL")
{
cell.parent().fadeOut("normal", function () {
$(this).remove();
});
}
else
{
$(".modal-body").html(result);
$("#myModal").modal();
}
},
error: function () {
alert("Something went wrong");
}
});
}
Recursive function GET partial view from ActionResult (MVC)
function RefreshRequests()
{
if (isListPage())
{
var id = PageId();
var url = "/Home/List/" + id;
}
else
{
var url = "/Home/Index";
}
$.ajax({
type: "GET",
url: url,
success: function (data) {
$(".ajaxRefresh").html(data);
EditPageHeader();
},
complete: function () {
setTimeout(RefreshRequests, 2000);
}
});
}
Click event
$(".tblRequests").on("click", button, function (e) {
e.preventDefault();
var id = $(this).data("id");
var currentRow = $(this).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
});
Main
$(document).ready(function () {
EditPageHeader();
RefreshRequests();
ButtonEvent(".btnPrepare", "/Home/Prepare/", "PREPARING");
ButtonEvent(".btnApprove", "/Home/Approve/", "APPROVED");
ButtonEvent(".btnCancel", "/Home/Cancel/", "CANCELED");
RefreshRequests();
});
Assumptions:
The Ajax Calls bring you data that end up as HTML elements in the modal body.
These new elements added above need to respond to the click event (the one that doesn't work correctly right now)
If the above 2 are true, than what is happening is you are binding events to existing elements (if any) and new elements (coming from API response) are not bound to the click event.
The statement
$(".tblRequests").on("click", button, function (e) {
...
})
needs to be executed every time new elements are added to the body. A better approach for this would be to define the event handler as an individual method and then bind it to each new element.
var clickHandler = function (e) {
e.preventDefault();
var id = $(this).data("id");
var currentRow = $(this).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
}
// Then for each new record that you add
$(".tblRequests").on("click", button, clickHandler);
It would be helpful if you can try to explain what exactly you are trying to achieve.
Problem is that the $(this) will hold all elements of the selector. And will also now with one as it will be triggered one time and then never again. Also as can be seen from here, delegate events should be at the closest static element that will contain the dynamic elements.
function ButtonEvent(button, url, state)
{
$("body").on("click", button, function (e) {
e.preventDefault();
var button = e.target;
var id = $(button).data("id");
var currentRow = $(button).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
});
}

How to disable all ng-click and ng-submit event

is there any way, how can I globally (in service) disable and enable all ng-click and ng-submit events?
For example when user is offline I want to disable all actions till he gets connection back..
I tried to bind all elements with an onClick event which will call stopImmediatePropagation but it didn't work..
$('*[ng-click]').click(function( event ) {
event.stopImmediatePropagation();
});
Also this question is a little bit different from this one:
Disable ng-click on certain conditions of application for all types of element
I'd like to disable/enable all events in APP globally from service, I'm not able to modify all ng-* calls on all elements in the APP..
Try including a return false too:
$('*[ng-click]').click(function( event ) {
event.stopImmediatePropagation();
return false;
});
Snippet
The below snippet demonstrates that multiple event handlers attached to a single <a> works too.
$(function () {
$("a").click(function () {
alert("Hello!");
return false;
});
$("a").click(function () {
alert("Bye!");
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
Click Me
So finally I end up with temporarily disabling all events on the page using jquery..
I got inspired from this plugin http://ignitersworld.com/lab/eventPause.html which for some reason did not work (without any error)
So I took main parts and put it to this class which is working now using jquery v2.1.1:
var EventManager = function() {
var self = this;
var nullFun=function(){};
var getIndex = function(array,value){
for(var i=0; i< array.length; i++){
if(array[i]==value){
return i;
}
}
return -1;
};
this.pauseEvent = function(elm,eventAry){
var events = $._data(elm, "events");
if (events) {
$.each(events, function(type, definition) {
if((getIndex(eventAry,type)!=-1)||(eventAry=='')){
$.each(definition, function(index, event) {
if (event.handler.toString() != nullFun.toString()){
if(!$._iwEventPause) $._iwEventPause = {};
$._iwEventPause["iw-event" + event.guid] = event.handler;
event.handler = nullFun;
}
})
}
})
}
};
this.activeEvent = function(elm,eventAry){
var events = $._data(elm, "events");
if (events) {
$.each(events, function(type, definition) {
if((getIndex(eventAry,type)!=-1)||(eventAry=='')){
$.each(definition, function(index, event) {
if (event.handler.toString() == nullFun.toString()){
event.handler = $._iwEventPause["iw-event" + event.guid];
}
})
}
})
}
};
this.disableAll = function(el) {
el = el || $('*');
el.each(function() {
self.pauseEvent($(this)[0], '');
});
self.pauseEvent($(window)[0], '');
};
this.enableAll = function(el) {
el = el || $('*');
el.each(function() {
self.activeEvent($(this)[0], '');
});
self.activeEvent($(window)[0], '');
};
return this;
};
var eManager = new EventManager();
eManager.disableAll();
eManager.enableAll();
This will go through window object and all elements on the page, move their event handlers away to _iwEventPause object and replace handlers with dummy function.. When enabling, it will move handlers back so they get normally called..
This solution does not handle event handlers added after disabling..

Managing and Maintaining too many on click jquery handlers

I recently have been upgrading the Phonegap to the latest version and now it forces me to follow the Chrome's Content Security Policy which in a way is good. But now I am forced to remove the all the onclick handlers in the HTML code and add them in the jquery handler some$(document).ready(function(evt){
$('#addRecordBtn').on('click', function(){
alert("Adding Record");
AddValueToDB();
});
$('#refreshBtn').on('click', function(){
alert("Refresh Records");
ListDBValues();
});
});
But as per what my app is scaled upto I feel that there will be too many of these handlers. Is there an example which shows maintenance of such handlers and a proper way or proper place of defining such handlers.
Here's an idea. You could make an object that stores all of the functions that also knows how to give up the function
var handlers = {
getHandler: function (str) {
return this[str];
},
'#addRecordBtn': function () {
alert("Adding Record");
AddValueToDB();
},
'#refreshBtn': function () {
alert("Refresh Records");
ListDBValues();
}
};
Then apply all of your handlers using this form.
$('#addRecordBtn').on('click', handlers.getHandler('#addRecordBtn'));
$('#refreshBtn').on('click', handlers.getHandler('#refreshBtn'));
Optimization Time if you want to get really fancy and you assign a unique ID to every button as convention
var handlers = {
defer: function () {
return function (){
handlers[$(this).attr('id')](arguments);
};
},
registerHandlers: function () {
for (var key in this) {
if (this.hasOwnProperty(key) && typeof(key) === "string") {
$('#' + key).on('click', this.defer());
}
}
},
'addRecordBtn': function () {
alert("Adding Record");
AddValueToDB();
},
'refreshBtn': function () {
alert("Refresh Records");
ListDBValues();
}
};
call it with
$('#addRecordBtn').on('click', handlers.defer());
$('#refreshBtn').on('click', handlers.defer());
or register everything automatically
handlers.registerHandlers();
Here is a fiddle of my solution
Do you look for something like this?
$('[data-clickhandler]').on('click', function(e) {
var $btn = $(e.currentTarget);
var handler = $btn.data('clickhandler');
alert('Refresh ' + handler);
window[handler] && window[handler](e);
e.preventDefault();
});
Now your elements can specify their clickhandler like so:
<a data-clickhandler="AddValueToDB" href="">...</a>
Or so:
<span data-clickhandler="ListDBValues">...</span>

Knockout.js Unobtrusive event handler not working

Here is I have table built with knockout 'foreach'. After user select some rows, these rows will contain class 'success'. So I want to use self.create event that fire after user press button (button located outside element that ViewModel binded to) in order to handle such table rows. But Firebug said: TypeError: GrafikViewModel.books is undefined.
Here is the code:
function InfoViewModel(baseUri) {
//some viewmodel here
}
//This is viewmodel I'm talking about.
function GrafikViewModel(grafikUri) {
var self = this;
self.books = ko.observableArray();
self.create = function () {
//Here we will handle tr with class 'success'
alert("!!!");
}
$.getJSON(grafikUri, function (data) {
self.books(data.$values);
});
}
$(document).ready(function () {
var url = location.href.split("/");
var baseUri;
var tkod = url[5];
if (url[4].toString = 'x') {
baseUri = '/api/xTourist/' + tkod;
}
else if (url[4].toString = 'y') {
baseUri = '/api/yTourist/' + tkod;
}
var grafikUri = '/api/grafik/' + tkod;
ko.applyBindings(InfoViewModel(baseUri), document.getElementById('info'));
ko.applyBindings(new GrafikViewModel(grafikUri), document.getElementById('grafik'));
$('#book').click(function () {
//Here I'm trying to call ViewModel.
GrafikViewModel.books.create(ko.dataFor(this));
});
});
try new GrafikViewModel().books.create(ko.dataFor(this));

Categories