Using jQuery to select checkboxes with click events - javascript

Is there a way to use jquery to select all checkboxes on a page that have an associated click event? I considered adding a class, for instance HasClickEvent, that I could use to identify such classes, but I am editing a huge script where click events are sporadically added all over the place and I think this would probably end up being messier, so a single jQuery call would be perfect

jQuery.each($('input[type=checkbox]').data('events'), function(i, event){
jQuery.each(event, function(i, handler){
if(handler.type.toString() == 'click')
{
// do something
}
});
});

To check all
$('.checkbox').attr('checked','checked'); // checkbox is the class for all checboxes to be selected change it with our own
To deselect all
$('.checkbox').removeAttr('checked');

A quick google reveals this plugin, but it's pretty old. You may be able to read the code and see how they are achieving it though :D

If the click events are attached using the onclick attribute (instead of added dynamically via JavaScript/jQuery), you can do it like this:
$("input[type=checkbox][onclick]").each(function() {
//All returned elements have an onclick attribute
});

Related

Possible to make div tags created using JQuery .html() clickable?

Hey guys bit of an odd questions but if I add div tags using JQuery .html() and give them an ID can I then use .click on them? The code might explain what I am trying to do. If not is there a possible work around?
I am trying to dynamically change my site without going to a new site.
So if I create Divs with an ID.
$("#funTime").click(function(){
var htmls = $("#content2").html();
$("#content2").html(htmls + " <div id='button1'>Create</div><div id='button2'>Annimate</div><div id='button4'>Clear</div>");
});
$("#button1").click(function(){create();});
$("#button2").click(function(){forannimation();});
$("#button3").click(function(){createOnMouse();});
It does not work but I do not know why.
Thanks in advance.
No you would need .on() to be able to handle dynamic added elements.
$('#content2').on('click', '#button1', function() {
// do your stuff
});
Also note that you can only add a single element with a certain id to the DOM. In your example everytime when the element with id #funTime is clicked you add en element with the same id.
You could improve your code by adding the button with some class instead of an id to the DOM or having a counter to produce unique ids. Or by preventing other clicks on #funTime by using .one() depending on your needs.
You can only assign an event handler to an element that exists. So the assignment of handlers should be done after the creation of the elements:
$("#funTime").click(function(){
var htmls = $("#content2").html();
$("#content2").html(htmls + " <div id='button1'>Create</div><div id='button2'>Annimate</div><div id='button4'>Clear</div>");
$("#button1").click(function(){create();});
$("#button2").click(function(){forannimation();});
$("#button3").click(function(){createOnMouse();});
});
However, several calls clicks on funtime will result in several elements with the same id, which results in an invalid document. Either prevent duplicate ids (e.g. implement a counter) or use classes.
You can actually create elements, bind events to them, all before they are on the screen. Backbone and others to it this way too.
var myNewDiv = $("<div ...>");
myNewDiv.click(function(){});
$(something).append(myNewDiv);
If you want to add events to things that are not yet on the page you must you use jQuery delegate.
You should use an on() listener for dynamically added elements
$("#content2").on('click','#button1',function(){create();});
This will add a listener to check for live added buttons in the selected container (#content2)
To do add thehandler as elements are created would need to add it within the click handler right after elements are appended....otherwise need to use delegation methods like on()
This would work:
$("#funTime").click(function(){
var htmls = $("#content2").html();
$("#content2").html(htmls + " <div id='button1'>Create</div><div id='button2'>Annimate</div><div id='button4'>Clear</div>");
/* elements exist can add event handlers*/
$("#button1").click(function(){create();});
$("#button2").click(function(){forannimation();});
$("#button3").click(function(){createOnMouse();});
});
More common current practice is to use delegation that allows for future elements and can be run on page load

using jQuery to change, only the elements that were loaded via ajax

For each checkbox on the web page, I replace it with a slider that I borrowed from jsfiddle.net/gnQUe/170/
This is done by going through the elements when the document is loaded.
Now the problem is that when more content is loaded via ajax, the new checkboxes are not transformed.
To solve the problem, I used AjaxComplete event to go through all the elements again and replace the checkboxes with sliders.
Now the problem happens that elements that were already replaced, get two sliders. To avoid that I check if the checkbox is hidden and next element is div of class "slider-frame", then don't process the re-process the element.
But I have a lot of other such controls as well, and I am presume I am not the only one that has this problem. Is there another easy way around it?
There exists jQuery live/on( http://api.jquery.com/on/ ) event but it requires an event as an argument? whereas I would like to change the look of my controls when they are rendered.
Another example of the same problem is to extend some controls that are loaded via ajax with jQuerys autocomplete plugin.
Is there a better way to accomplish this other than changing some attributes on the element.
To summarize, on document load I would like to process every element in DOM, but when more elements are loaded via ajax then I want to change only the new elements.
I would assume that when the element's are transformed into a slider, a class is added to them. So just add a not clause.
$(".MySelector").not(".SomeClassThatSliderAddsToElement").slider({});
So in the case of your code do something like this
$('.slider-button').not(".sliderloaded").addClass("sliderloaded").toggle(function(){
$(this).addClass('on').html('YES');
$('#slider').val(true);
},function(){
$(this).removeClass('on').html('NO');
$('#slider').val(false);
});
Since you said you do not want to add anything else, how about you change the toggle function to click.
$(document).on("click", ".slider-button", function(){
var elem = $(this);
elem.toggleClass("on");
var state = elem.hasClass("on");
elem.text(state?"YES":"NO");
elem.parent().next().val(state);
});
Running fiddle: http://jsfiddle.net/d9uFs/

jQuery dynamic checkbox event handling

When appending HTML from a JSON reply, the event handlers appear to lose their event bindings. In using the .live() function the handler now appears to work.
$.each(result[0], function(i,wellList) {
$jsonResult = wellList["#name"];
$uid = wellList["#uid"];
$dynamicCheckBoxDiv += '<input type="checkbox" name="checkbox-1" value="'+ $uid
+ '" class="wellCheck" id="checkbox-'+i+'" />' +
'<label for="checkbox-'+i+'">' + $jsonResult + '</label>';
});
$dynamicCheckBoxDiv += '</fieldset></div>';
//Append results to div
$("#dynamicCheck").append($dynamicCheckBoxDiv).page();
$(".wellCheck").live('click', (function() {
This event now fires when the click function is run. However, after clicking the checkbox a few times, it randomly associates the checks with the wrong boxes and starts to fire the click event fire on a single click. Has anyone seen this before?
Also: How could I add a method to check all the boxes in a separate button? Since they are being added dynamically it seems to just bypass this function:
// When select No wells is clicked this method is run
$('#selectNone').click(function() {
$('#dynamicCheck .wellCheck').find(':checkbox').attr('checked', 'checked');
});
It enters the method, but doesnt seem to check any of the boxes. I have jQuery and jQuery mobile added to this page and both methods exist under document.ready.
You don't need to find(":checkbox") since the .wellCheck element is the checkbox. Just do this:
$("#selectNone").click(function(){
$("#dynamicCheck .wellCheck").prop("checked", true);
});
Demo.
Explanation of the first bit is that the written-into-HTML listeners only apply on page load. Any time you're adding raw HTML to the page, you have to set any listeners specifically. Similarly, just changing the "onclick" attribute does nothing to the listeners.
I suspect your problem with the second bit has something to do with the fact that, at least by my reading, '$(".wellCheck").live(...)' is going to affect every box you've created thus far each time. You might be better served by something like '$dynamicCheckBoxDiv.live(...)'
I'm not entirely clear on the precise syntax - I worked more with cloned HTML rather than manually constructed, so you may need an intervening step to render it into a DOM object or something (if it's not one already) - but I suspect something like this will help.
Also, you might wish to use '.click(...)', rather than '.live("click", ...)'.
You should use delegate not live:
$("#dynamicCheck").delegate('.wellcheck','click', function(){
//stuff on click
});
This would be better bound at that scope than at the body which is what live does.
EDIT: See this for some examples of checkbox management: http://jsfiddle.net/h682v/3/
That uses older attr() and should use prop() instead but the principle remains.

Recursive jQuery function to amend select option values

I have a form that I am trying to alter with jQuery. Basically, my form has two elements and I need to change the value of the first option in each of them. However, there is an "add more" option that uses AJAX to dynamically generate another element that also needs changed. This add more button can be clicked an unlimited amount of times.
Right now I have this:
$(document).ready(function(){
$("#myname-0-field option:first").val("None");
$("#myname-1-field option:first").val("None");
});
This works fine, but once the "add more" button is clicked, I have more elements called "#myname-2-field", "#myname-3-field", "#myname-4-field" etc. These obviously aren't affected by adding another line into my jQuery as the document has already loaded when they are added.
So the real question is, can someone point me in the right direction of writing a function that can react when the new element is added and change it. If possible, I'm also looking for the function to be aware and look for "#myname-X-field option:first" for tidyness.
use live() function
Then using each function set value
From the jQuery API look live function
Maybe you could add class to your element, so that finding particular element would be easier and it would not add event to other similar elements.
In the example I have a Li with class
$('li.myClass').live('click', function() {
$(this).val(); // this is the getter for clicked value
$(this).val("some_value_here"); // this is the setter for clicked value
});
Now you can add more elements (that has myClass class) and it will have a click event.
Btw. if you know that all elements are inside some container (div for example) then you can write more efficient jQuery using delegate.
$('#container_id').delegate('li.myClass', 'click', function () {
});
This is more efficient because it looks your new elements only under "containter" not from the whole DOM structure.

Using jQuery on dynamically added content

I am newbie to jQuery and javascript. In my application I have a list of users. When a particular user is clicked from the list, a div element is replaced with details about the user dynamically. When another user is clicked, again I replace the same div element with this user details. So at a time only one user details can be seen.
I use jquery, so my code to the above description looks like.
$('table#moderate_users tr').click(function() {
$.get('/moderate/user/'+uid, function(data){ $('div.user_info').html(data);
});
});
This works perfect and the content is inserted dynamically.
I have a dropdown(html select tag) in the dynamically added content. So I get the dropdown only when i click on a user from the list and it changes repectively when I click on another user. I wanted to find the value of the select tag using jquery whenever it is changed. So I wrote
$('select#assign_role').change(function(){
alert(this.val());
});
Since this dropdown is added after document.ready, adding this script inside document.ready function never worked. I also tried to insert the above script along the with the user details which is dynamically added.For my surprise this script is not inserted into the document at all, while the rest of the HTML content are inserted perfect. I am not aware if i can add insert javascript after the document has loaded. I am not aware how i could use jQuery to find out the value of the select tag which is added dynamically.
Thanks.
you want jQuery's "live" functionality:
$('select#assign_role').live('change',function(){
alert($(this).val());
});
also notice I changed alert(this.val()); to alert($(this).val()); considering that this inside a jQuery event handler references the actual dom element, not a jQuery object.
From the looks of your code, it seems that you are inserting a chunk of HTML into that div. So even if you wire your event to the dropdown after the page load, it will not work, since all of your event binding will be ignored when you insert new HTML code into div.
Try moving your code inside the function that inserts HTML. Something like this:
$('table#moderate_users tr').click(function() {
$.get('/moderate/user/'+uid, function(data){
$('div.user_info').html(data);
$('select#assign_role').change(function(){
alert(this.val());
});
});
});
On IE the live function doesn't work for onchange on <select> elements.
http://www.neeraj.name/blog/articles/882-how-live-method-works-in-jquery-why-it-does-not-work-in-some-cases-when-to-use-livequery
You will need to either add the select then do a setTimeout and then bind with the jquery.bind type of functionality, or, what I have done, is when you create the element then just set the onchange event handler there directly.
If you don't need to support IE then the live function works great.

Categories