Unable to call .click function - Jquery - javascript

I'm creating a Firefox/Chrome Addon that goes on a 3rd party website. On this site, there is a list of about 512 names in one ul. I want to put 12 of them, based on their values and compared to an array.
Each li item looks like so:
<li><a class="manip" href="javascript:void(0);"></a><span class="draggable in-MultiCheckPossibleUserIdslistpair-possible ui-draggable"><a class="user" href="javascript:jQuery.wp.showModalWindow('/OneProof/User/Info/31654022')">Aaron Quinby</a><span class="id">31654022</span><span class="sortNo">1</span></span><span class="preview" style="display: none;">Aaron Quinby</span></li>
Right now, clicking on the a tag, with manip class will bring the li item from one ul to the correct ul. I want to do this automatically with my addon. I figured the quickest way would be to call the .click() event with jQuery on the a tag like so:
$(document).ready(function() {
$(".manip").each(function() {
//quick check to see if it works, click all
$(this).click();
});
});
I've played with the click, calling it in the console, calling it after a delay, and few other ways.
The only JavaScript I can find associated with the manip class in the source for this site is the following:
universe.find("a.manip")
.click(function() {
//alert("bound");
$.dropIt($(this).parent(), false);
});
Is there a reason why the .click call event isn't working?
Thanks!
Edit: Universe is defined here:
function listpairCore(options) {
var options = $.extend({}, $.fn.listPair.options, options);
var thisId = this.attr("id");
var ulSelected = this.find("ul.selected");
var ulPossible = this.find("ul.possible");
var universe = this;
and listpaircore is called here
$.fn.listPair = listpairCore;

The click function does not simulate a click. It binds an event handler to the click event.
What you want is
$(this).trigger( "click" );
Update:
The javascript you found in the source references the "manip" class as
universe.find("a.manip")
so maybe try doing the same?
$(document).ready(function() {
universe.find("a.manip").each(function() {
//quick check to see if it works, click all
$(this).trigger("click");
});
});

Related

JQuery select elements in <span> that doesn't exist initially

I've been looking for so long and found several answers that suggest using .on() as in $('.idOfMyElemenet').on() works even for elements that don't exist yet. But this doesn't seem to be finding the element. Am I doing something wrong?
The highest level <span> (in screenshot) does not exist until I click on a drop-down. Ultimately I'm trying to trigger an event when the user clicks on any of the <li> (aka selects an option from the drop-down).
$(document).ready(function () {
var test = "#select2-id_customer-results";
$(test).on("click", function() {
console.log('hello')
})
})
EDIT:
Thanks to Drew Baker - I think his second solution is the way to go. But not quite there yet...
From the select2 documentation
All public events are relayed using the jQuery event system, and they
are triggered on the <select> element that Select2 is attached to.
So I tried listening to it via the id (which doesn't seem to exist but would probably be id_customer) and the class. The class I added below did not work. Is there a way to listen to this using Jquery?
$(document).ready(function () {
// console.log($('#id_customer'));
$('.modelselect2 form-control select2-hidden-accessible').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
});
I'll answer your question, but then give you a better solution.
First, you need to make sure the thing you are attaching .on() to actually exists. I typically use a containing DIV or failing that body or html will work.
Secondly you are missing a parameter that tells jQuery the thing you are looking to watch to be clicked on. In this case, I'm assuming it is the UL tag with the ID you provided.
This should do what you want:
$(document).ready(function () {
$('body').on("click", "#select2-id_customer-results", function() {
console.log('hello')
})
})
But a better solution would be to use the Select2 API to have it tell you when something is selected. This will be way more reliable and should make your code work after upgrades to Select2.
Something like this:
$('select[name="customer"]').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
NOTE: #mySelect2 is probably not what you have. Use whatever ID you used to initialize Select2 in jQuery.
You can read more about that API here: https://select2.org/programmatic-control/events
if your element is dynamically generated and you want to target that specific element. You need to specify a static container/parent element to indicate where it belongs.
Try this:
$( '#dynamicallyAddedElement' ).on( 'click', '#wrapper', function () { ... });
//where #wrapper is a static parent element in which you add the dynamic links.
So, you have a wrapper which is hard-coded into the HTML source code:
PS. Hope I helped in some way.
If you need to trigger an event when click on <li> elements, you have to use that elements id or class as the selector. Check the below code:
$(document).ready(function () {
var test = ".select2-results__option";
$(test).on("click", function() {
console.log('hello')
})
})
It turns out this is an old bug in django-auto-complete.
The code below works. I have no idea why but now I can move on.
Note: the 'name' is the value of the select2 select element (see screenshot at bottom)
document.querySelector('select[name="customer"]').onchange=function() {
console.log("myselect2name changed");
};

jQuery continuously running an event

I have the following code which checks for the id of the active tab BUT only once when the page initially loads.
jQuery(document).ready(function(){
var id_of_tab = jQuery('#member-registration .tab-pane.active').attr('id');
console.log(id_of_tab);
});
I need this code to continuously check for the id of the active tab, (as there are various ways in which the user can make this tab active, and I have tried many click and hover events but ive found issues with all of them).
Rather than firing on a click/hover (such as the example below) the code needs to simple needs to keep running and to change the variable value if the active tab changes.
jQuery(document).ready(function(){
$( ".view-registration" ).hover(
function() {
var id_of_tab = jQuery('#member-registration .tab-pane.active').attr('id');
console.log(id_of_tab);
});
});
I'm struggling on this one!
You can bind multiple events on one function handler.
The 4 I suggest here are only suggestion for the code example`
It's up to you to determine the right events to bind.
See list here: http://www.quirksmode.org/dom/events/
$(document).ready(function(){
$( "#member-registration" ).bind("change mouseover click input",function(){
var id_of_tab = $(this).attr('id'); // Will alway return #member-registration
console.log(id_of_tab);
// Suggested console message ;)
console.log("An event occured on #member-registration");
// Maybe a check for the `active` class?
if( $(this).hasClass("active") ){
console.log("#member-registration is active.");
}
});
});

Click Event inside of a jQuery Plugin on another element doesn't work

I found many articles about this topic on stackoverflow but no one gave me a solution on my exact problem.
I have a jQuery Plugin which works fine so far. In that plugin I add some new DIVs. Also I want to add a click event listener on these new DIVs. Like this:
(function ($) {
$.fn.myFunc = function(options) {
// Options + Defaults
var settings = $.extend({
// Some options in here
}, options);
var controls = "\
<div class='controls'>\
<button class='btn-add-text'>Add Text</button>\
</div>\
";
$('.btn-add-text').click(function() {
alert("Test");
});
$(this).after(controls);
return this;
};
})(jQuery);
My first thought was, that it is not possible because the event listener was called before the new div is actually inside of the DOM, so it can't work. So I moved the .click(func... Block outside of the plugin code and put it inside of a document.ready function like so:
$(document).ready(function() {
$('.btn-add-text').click(function() {
alert("Test");
});
});
This also won't work for me. Is there any solution for this problem?
Try to use more variables to store html (jquery) elements.
(function ($) {
$.fn.myFunc = function(options) {
// Options + Defaults
var settings = $.extend({
// Some options in here
}, options);
var button = $('<button class="btn-add-text">Add Text</button>');
button.click(function() {
alert("Test");
});
var controls = $('<div class="controls"></div>')
.append(button);
$(this).after(controls);
return this;
};
})(jQuery);
You use $('.btn-add-text').click( ... ) and then you add this element to html with $(this).after(controls). So jquery selector function can't find this element in html, becouse it is not here.
Also your concept isn't correct, becouse you add event listener on all elements .btn-add-text every time you call myFunc which can overload client javascript. Add event listeners only to elements that you are currently creating.
To make it work on new DIVs you have to do something like -
$('.controls .btn-add-text').click(function() {
alert("Test");
});
If it doesn't work, then try disabling the cache and refresh.
Edit:
Overlooked something. Actually you are just registering the inner function(with 'options' parameter). You need to get it run to add the actual div element.
Your outer function is running because it is enclosed in () but the inner one is not.

trigger('click') doesn't work on anchors without an actuall link in the href ( js function in the href attrbute )

i have some links for confirming comments
<a class="confirm_btn" href="javascript:confirm_ajax(17)" id="confirm_17">Confirm</a>
<a class="confirm_btn" href="javascript:confirm_ajax(20)" id="confirm_20">Confirm</a>
i want to be able to confirm all at once with one click , i know it's probably better to get all ids in an array and send them with one ajax call to backend script but for some reason i prefer not to do that and click each button .
here is my jq code
function confirm_all(){
$('.confirm_btn').each(function(index, element) {
$(this).trigger('click');
// also i've tried $(this).click();
console.log($(this).attr('id'));
});
}
when i run this i get the console.log result
confirm_17
confirm_20
confirm_22
confirm_33
confirm_34
but the click part doesn't work , it suppose to fire confirm_ajax function ... no error in the firebug .... if i click on the buttons they work fine
trigger('click') will only invoke attached event handlers; if you have JavaScript hrefs, they won't be triggered.
You could try attaching regular click handlers to your links, or you could do something like this instead:
var idFormat = /confirm_(\d+)/;
$('.confirm_btn').each(function() {
var btn = $(this);
var id = parseInt(idFormat.exec(btn.attr('id'))[1], 10);
confirm_ajax(id);
});

Add click event to Div and go to first link found

I think I've been too much time looking at this function and just got stuck trying to figure out the nice clean way to do it.
It's a jQuery function that adds a click event to any div that has a click CSS class. When that div.click is clicked it redirects the user to the first link found in it.
function clickabledivs() {
$('.click').each(
function (intIndex) {
$(this).bind("click", function(){
window.location = $( "#"+$(this).attr('id')+" a:first-child" ).attr('href');
});
}
);
}
The code simply works although I'm pretty sure there is a fairly better way to accomplish it, specially the selector I am using: $( "#"+$(this).attr('id')+" a:first-child" ). Everything looks long and slow. Any ideas?
Please let me know if you need more details.
PS: I've found some really nice jQuery benchmarking reference from Project2k.de here:
http://blog.projekt2k.de/2010/01/benchmarking-jquery-1-4/
Depending on how many of these div.click elements you have, you may want to use event delegation to handle these clicks. This means using a single event handler for all divs that have the click class. Then, inside that event handler, your callback acts based on which div.click the event originated from. Like this:
$('#div-click-parent').click(function (event)
{
var $target = $(event.target); // the element that fired the original click event
if ($target.is('div.click'))
{
window.location.href = $target.find('a').attr('href');
}
});
Fewer event handlers means better scaling - more div.click elements won't slow down your event handling.
optimized delegation with jQuery 1.7+
$('#div-click-parent').on('click', 'div.click', function () {
window.location.href = $(this).find('a').attr('href');
});
Instead of binding all the clicks on load, why not bind them on click? Should be much more optimal.
$(document).ready(function() {
$('.click').click(function() {
window.location = $(this).children('a:first').attr('href');
return false;
});
});
I would probably do something like;
$('.click').click(function(e){
window.location.href = $(this).find('a').attr('href');
});

Categories