Use from `$.each` in several times separate.? - javascript

After search and click on result search and click on plus(button add input) next to input "INSERT VALUE HERE" in the example, in new input $('.auto_complete').keyup(function () { ... not work.
I believe that have to bind the events separately and use a closure so that each element has its own set of variables(or change the logic so that only use the value in the field and don't need any state variables),
how is it?
EXAMPLE: see here
Js full code: http://jsfiddle.net/6yPxn/
$.each:
var ac = $(this).text();
var ok = $.grep(data, function (e) {
return e.name == ac;
})[0].units;
$.each(ok, function (bu, key) {
//alert(key.name_units);
$("<div class='mediumCell'/>").hide().fadeIn('slow').append('<b>' + key.name_units + '</b>', $('<div class="column" style="float: left;" />')).appendTo(".list_units");
});

It runs fine, but I don't see anywhere in that code you've provided where you're adding an event handler to the input box.
The issue is in http://www.binboy.gigfa.com/files/js/admin.js, somewhere around the top:
$('.auto_complete').bind('keyup',function () {
/* ... */
});
When the page loads it binds several event handlers to input boxes and the like. When you create a new one this functionality is not added unless you're using jQuery's .live or something similar. As the documentation notes:
This method [.live()] is a variation on the basic .bind() method for attaching event handlers to elements. When .bind() is called, the elements that the jQuery object refers to get the handler attached; elements that get introduced later do not, so they would require another .bind() call.
I don't really want to wade through all the nested click and delegate and bind calls, but I guarantee you that's where your problem lies. To fix it you'll probably need to have either the autocomplete section run on your newly created node, use .live instead, or just .clone the original.

Related

Changed data attribute not recognized in jquery selector

I've the following html structure
<body data-page="first">
<div class="start">Test</div>
</body>
and the following js
$('body[data-page="first"] .start').on('click',function (){
body.attr('data-page','second');
});
$('body[data-page="second"] .start').on('click',function (){
console.log('Test');
});
I would expect, that after the second click on .start, the console would show "Test", but it doesn't...
Can you tell me what I'm doing wrong?
Thanks in advance!
While you have your answer, I don't think the essential point has been made in any of the answers so far, and that is that the binding of an event handler must happen after the target element exists.
When you try to bind an event handler to a particular element in the DOM, the element must exist at the time. If it does not exist, the handler has nothing to bind to, and so the binding fails. If you later create the element, it's too late, unless you re-run the binding statement.
It will soon become second nature to call appropriate event handler binding statements after you create a new element (by modifying the HTML using javascript) that needs a handler.
For instance, in my current project I regularly make AJAX calls to a server to replace blocks of HTML as things happen on the page. Even if some of the new elements are exactly the same as the ones being replaced, they will not inherit any bindings from the replaced elements. Whenever I update the HTML I call a function that contains necessary statements to bind my event handlers to the new copy of the active elements.
Your code would work if you made the following change:
$('body[data-page="first"] .start').on('click',function ()
{
body.attr('data-page','second');
$('body[data-page="second"] .start').on('click',function (){
console.log('Test');
});
})
A couple of other (off-topic, but related) points:
It's possible to bind a handler to an element multiple times. The trick to avoiding this is to include the .off() method in the chain before binding (noting though that .off("click") will unbind all click handlers bound to that element, not just yours) e.g.
$("#mybutton").off("click").click(function(){myHandler()});
"the arrow function doesn’t have its own 'this' value" () so don't use arrow functions in event handlers if you plan to reference any of the element's properties via 'this'. e.g.
$("#mybutton").off("click").click(() => {console.log(${this.id})}); // >> "undefined"
The issue is that the page is rendered with the data-page set to first, and when you click again on it, that part of javascript still see "first", since is not rerendered, so you need a dynamic function, the read all the intereaction with that button, and than check wich value that attribute has. Like this you can make infinite cases, and still go on.
$('body .start').on('click',function (){
const attr = $('body').attr('data-page');
if(attr === 'first') {
$('body').attr('data-page','second');
} else {
console.log('second');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body data-page="first">
<div class="start">Test</div>
</body>
And if you don't like the fact that is targetting all the "body" wich is weird, becouse you should have only 1 body, you can use an ID to target the right one
PS: is never a good idea to duplicate your function, if you can set everything in a dynamic function, that reads everything, is easier to debug in the feature, and is lighter and more clean to work on
$('body[data-page="first"] .start').click(function (){
var body = $('body[data-page="first"] .start');
body.attr('data-page','second');
});
This method can help :
var timesClicked = 0;
$('.start').on('click',function (){
timesClicked++;
if (timesClicked>1) {
console.log('Test');
}
});

jQuery remove scroll listener after reach certain point [duplicate]

I have an input type="image". This acts like the cell notes in Microsoft Excel. If someone enters a number into the text box that this input-image is paired with, I setup an event handler for the input-image. Then when the user clicks the image, they get a little popup to add some notes to the data.
My problem is that when a user enters a zero into the text box, I need to disable the input-image's event handler. I have tried the following, but to no avail.
$('#myimage').click(function { return false; });
jQuery ≥ 1.7
With jQuery 1.7 onward the event API has been updated, .bind()/.unbind() are still available for backwards compatibility, but the preferred method is using the on()/off() functions. The below would now be,
$('#myimage').click(function() { return false; }); // Adds another click event
$('#myimage').off('click');
$('#myimage').on('click.mynamespace', function() { /* Do stuff */ });
$('#myimage').off('click.mynamespace');
jQuery < 1.7
In your example code you are simply adding another click event to the image, not overriding the previous one:
$('#myimage').click(function() { return false; }); // Adds another click event
Both click events will then get fired.
As people have said you can use unbind to remove all click events:
$('#myimage').unbind('click');
If you want to add a single event and then remove it (without removing any others that might have been added) then you can use event namespacing:
$('#myimage').bind('click.mynamespace', function() { /* Do stuff */ });
and to remove just your event:
$('#myimage').unbind('click.mynamespace');
This wasn't available when this question was answered, but you can also use the live() method to enable/disable events.
$('#myimage:not(.disabled)').live('click', myclickevent);
$('#mydisablebutton').click( function () { $('#myimage').addClass('disabled'); });
What will happen with this code is that when you click #mydisablebutton, it will add the class disabled to the #myimage element. This will make it so that the selector no longer matches the element and the event will not be fired until the 'disabled' class is removed making the .live() selector valid again.
This has other benefits by adding styling based on that class as well.
This can be done by using the unbind function.
$('#myimage').unbind('click');
You can add multiple event handlers to the same object and event in jquery. This means adding a new one doesn't replace the old ones.
There are several strategies for changing event handlers, such as event namespaces. There are some pages about this in the online docs.
Look at this question (that's how I learned of unbind). There is some useful description of these strategies in the answers.
How to read bound hover callback functions in jquery
If you want to respond to an event just one time, the following syntax should be really helpful:
$('.myLink').bind('click', function() {
//do some things
$(this).unbind('click', arguments.callee); //unbind *just this handler*
});
Using arguments.callee, we can ensure that the one specific anonymous-function handler is removed, and thus, have a single time handler for a given event. Hope this helps others.
maybe the unbind method will work for you
$("#myimage").unbind("click");
I had to set the event to null using the prop and the attr. I couldn't do it with one or the other. I also could not get .unbind to work. I am working on a TD element.
.prop("onclick", null).attr("onclick", null)
If event is attached this way, and the target is to be unattached:
$('#container').on('click','span',function(eo){
alert(1);
$(this).off(); //seams easy, but does not work
$('#container').off('click','span'); //clears click event for every span
$(this).on("click",function(){return false;}); //this works.
});​
You may be adding the onclick handler as inline markup:
<input id="addreport" type="button" value="Add New Report" onclick="openAdd()" />
If so, the jquery .off() or .unbind() won't work. You need to add the original event handler in jquery as well:
$("#addreport").on("click", "", function (e) {
openAdd();
});
Then the jquery has a reference to the event handler and can remove it:
$("#addreport").off("click")
VoidKing mentions this a little more obliquely in a comment above.
If you use $(document).on() to add a listener to a dynamically created element then you may have to use the following to remove it:
// add the listener
$(document).on('click','.element',function(){
// stuff
});
// remove the listener
$(document).off("click", ".element");
To remove ALL event-handlers, this is what worked for me:
To remove all event handlers mean to have the plain HTML structure without all the event handlers attached to the element and its child nodes. To do this, jQuery's clone() helped.
var original, clone;
// element with id my-div and its child nodes have some event-handlers
original = $('#my-div');
clone = original.clone();
//
original.replaceWith(clone);
With this, we'll have the clone in place of the original with no event-handlers on it.
Good Luck...
Updated for 2014
Using the latest version of jQuery, you're now able to unbind all events on a namespace by simply doing $( "#foo" ).off( ".myNamespace" );
Best way to remove inline onclick event is $(element).prop('onclick', null);
Thanks for the information. very helpful i used it for locking page interaction while in edit mode by another user. I used it in conjunction with ajaxComplete. Not necesarily the same behavior but somewhat similar.
function userPageLock(){
$("body").bind("ajaxComplete.lockpage", function(){
$("body").unbind("ajaxComplete.lockpage");
executePageLock();
});
};
function executePageLock(){
//do something
}
In case .on() method was previously used with particular selector, like in the following example:
$('body').on('click', '.dynamicTarget', function () {
// Code goes here
});
Both unbind() and .off() methods are not going to work.
However, .undelegate() method could be used to completely remove handler from the event for all elements which match the current selector:
$("body").undelegate(".dynamicTarget", "click")
I know this comes in late, but why not use plain JS to remove the event?
var myElement = document.getElementById("your_ID");
myElement.onclick = null;
or, if you use a named function as an event handler:
function eh(event){...}
var myElement = document.getElementById("your_ID");
myElement.addEventListener("click",eh); // add event handler
myElement.removeEventListener("click",eh); //remove it
This also works fine .Simple and easy.see http://jsfiddle.net/uZc8w/570/
$('#myimage').removeAttr("click");
if you set the onclick via html you need to removeAttr ($(this).removeAttr('onclick'))
if you set it via jquery (as the after the first click in my examples above) then you need to unbind($(this).unbind('click'))
All the approaches described did not work for me because I was adding the click event with on() to the document where the element was created at run-time:
$(document).on("click", ".button", function() {
doSomething();
});
My workaround:
As I could not unbind the ".button" class I just assigned another class to the button that had the same CSS styles. By doing so the live/on-event-handler ignored the click finally:
// prevent another click on the button by assigning another class
$(".button").attr("class","buttonOff");
Hope that helps.
Hope my below code explains all.
HTML:
(function($){
$("#btn_add").on("click",function(){
$("#btn_click").on("click",added_handler);
alert("Added new handler to button 1");
});
$("#btn_remove").on("click",function(){
$("#btn_click").off("click",added_handler);
alert("Removed new handler to button 1");
});
function fixed_handler(){
alert("Fixed handler");
}
function added_handler(){
alert("new handler");
}
$("#btn_click").on("click",fixed_handler);
$("#btn_fixed").on("click",fixed_handler);
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn_click">Button 1</button>
<button id="btn_add">Add Handler</button>
<button id="btn_remove">Remove Handler</button>
<button id="btn_fixed">Fixed Handler</button>
I had an interesting case relevant to this come up at work today where there was a scroll event handler for $(window).
// TO ELIMINATE THE RE-SELECTION AND
// RE-CREATION OF THE SAME OBJECT REDUNDANTLY IN THE FOLLOWING SNIPPETS
let $window = $(window);
$window.on('scroll', function() { .... });
But, to revoke that event handler, we can't just use
$window.off('scroll');
because there are likely other scroll event handlers on this very common target, and I'm not interested in hosing that other functionality (known or unknown) by turning off all of the scroll handlers.
My solution was to first abstract the handler functionality into a named function, and use that in the event listener setup.
function handleScrollingForXYZ() { ...... }
$window.on('scroll', handleScrollingForXYZ);
And then, conditionally, when we need to revoke that, I did this:
$window.off('scroll', $window, handleScrollingForXYZ);
The janky part is the 2nd parameter, which is redundantly selecting the original selector. But, the jquery documentation for .off() only provides one method signature for specifying the handler to remove, which requires this middle parameter to be
A selector which should match the one originally passed to .on() when attaching event handlers.
I haven't ventured to test it out with a null or '' as the 2nd parameter, but perhaps the redundant $window isn't necessary.

JQuery: Best way to bind events to dynamically created elements

Consider the following:
var template = '<div class="dynamic">Some markup</div>'
, $template = $(template);
$template.on('click.namespace.data-api', function(e) { doStuff() });
$('div.#parent').append($template);
To me, this seems to be the most optimal way to bind an event to a node, since the event is attached to a node that has already been introduced as a jQuery object. However, I'm not sure how this plays out during actual click events; on click, is jQuery able to find this element immediately since the event is bound to a jQuery object? Or is it more optimal to bind the event using something like:
var template = '<div class="dynamic">Some markup</div>'
, $template = $(template);
$('div.#parent').append($template);
$('div.#parent').on('click.namespace.data-api', 'div.dynamic', function(e) { doStuff() });
JQuery objects only persist in the exact call they are in. As soon as that call is done the object no longer is related as a JQuery object.
As you are showing with click delegation you wont have to worry about the dynamic aspect of the element being created at any moment, because the handler is hooked to the parent node, then watches for click on the delegated element/class.
Writing the second version of click delegation using the direct delegation method to me is much easier to read, and is more clear when you come back to read again in the future.
Instead of binding event to the specific element, you can bind it to document instead.
`$('.dynamic').click()` can be replaced with `$(document).on('click', '.dynamic', function())`

Rebind a JQuery function to an input field after innerHTML command

Im using JQuery to check the file size and name from an html file input field. The input field is:
<div id="uploadFile_div">
<input name="source" id="imageFile" type="file" style ="border: 1px solid #576675;">
</div>
And the JQuery:
$(document).ready(function(){
$('#imageFile').bind('change', function() {
alert("Test");
//.... perform input checks...//
});
});
Now, I have a selection box, where the user choose between image file or video file, and based on it I send the file to different servers and also perform appropriate checks. In order to reset the input field (I do it when the user changes the selection box from Video to Image and vise versa) I use this JavaScript trick:
document.getElementById('uploadFile_div').innerHTML = document.getElementById('uploadFile_div').innerHTML;
But After 1 execution of this JavaScript, The JQuery isn't binded and I don't see the "Test" alert when I select files.
How can i rebind the JQuery ?
Thanks.
You could use a delegated event handler, binding the event to the parent div:
$('#uploadFile_div').on('change','#imageFile', function() {
// etc
Demo: http://jsfiddle.net/SfgpS/
(If you're using a version of jQuery older than 1.7 use .delegate() instead of .on(). If you're using a really old version of jQuery use .live().)
When you rewrite the .innerHTML of the container that effectively erases the old input element including event handlers that were bound to it, and then creates a new input. So you could re-run your original .bind() statement at that point to bind a handler to the new input.
With a delegated event handler as for that syntax of .on() you bind the handler to the container, i.e., to the div in this case. Events that happen to the container's child(ren) bubble up to the container (and then right on up to the document). So in this case when a change event reaches the div jQuery checks whether it originated with an element matching the selector from the second parameter of .on() and if so calls the your handler function. This lets you handle events on elements that don't exist at the time you create the handler. It doesn't matter if you remove and re-add the child elements because the handler was bound to the container.
(Note that if you leave out that second parameter to .on() it creates a non-delegated handler just the same as .bind().)
Why not just wrap the whole mess up in a function you can call both onReady and then whenever you want to reset the upload form?
var resetUpload = function() {
document.getElementById('uploadFile_div').innerHTML = document.getElementById('uploadFile_div').innerHTML;
$('#imageFile').bind('change', function() {
alert("Test");
//.... perform input checks...//
});
}
// run on ready
$(document).ready(function () {
resetUpload();
});
What version of jQuery are you using?
You could use .live() or .on() (jQuery >= 1.7) instead of .bind()

Fire a function on a element

I need to add a color picker to some input elements.
I'm using:
$(".element").colorPicker(){ ... }
This works perfectly.
The problem is that the page has a AJAX form, which - when submitted - will overwrite the previous form with a new one (new input fields etc). After that the colorPicker stops working.
So how can I fire that function to the newly created inputs too?
Just reattach the invocation in the ajax callback, since I don't believe there is a reliable event you can use to .live or .delegate it, without revealing more information.
I believe this might work:
$(".element").live('click focus', function () {
var $this = $(this);
if (!$this.data('hasColorPicker')) {
$this.colorPicker({ /* ... */ }).data('hasColorPicker', true);
$this.click(); // trigger the color picker - assuming it binds itself to the click event
}
});
What meder says is good, but also, if you are creating the new elements by copying existing ones, consider using $.clone(true) to make your copies and it will carry over existing event bindings too.

Categories