jQuery Bind each() and also click() on the same function - javascript

So I have the following fragment:
$(".server").each(function() {
var element = $(this);
//bunch of javascript here with element
});
I also want to bind a single click event for an id to do the same work as the above, how is this possible, without copying and pasting the entire block and doing:
$("#my-id").click(function() {
var element = $(this);
//bunch of javascript here with element
});

I think the following should work:
var eventHandler = function() {
var element = $(this);
//bunch of javascript here with element
};
$(".server").each(eventHandler);
$("#my-id").click(eventHandler);

Related

How to let onclick(); listens to more than one button

I am trying to let Jq listen to three buttons at the same onclick method
then trigger a function and call the clicked button by $(this);
here is a sample :
$("body").on('click', 'a.home:visible', 'a.mobile:visible', 'a.phone:visible', function () {
var attr = $(this).attr('attr');
$(this).parents('.dropdown-menu').prev().prev().text(attr);
});
You did it basically correct. Your approach is fine. But you have to combine it in one string, not as single parameters. And you don't need :visible, because you can't click on invisible elements. ;)
$("body").on('click', 'a.home, a.mobile, a.phone', function() {
var attr = $(this).attr('attr');
$(this).parents('.dropdown-menu').prev().prev().text(attr);
});
If the elements are static you should even use a normal event listener instead of a delegation.
$('a.home, a.mobile, a.phone').click(function() {
var attr = $(this).attr('attr');
$(this).parents('.dropdown-menu').prev().prev().text(attr);
});
Put them in one quotes
$("body").on('click', 'a.home:visible,a.mobile:visible,a.phone:visible', function() {
alert('Clicked')
});
JSFIDDLE

How to append a dynamic div in AngularJS?

.directive('mydirective', [function($scope, $document,windowService) {
return{
link : function(scope,element,attars){
--- Some more code —--
var containers = $('.container’);
containers.bind('click', function(event) {
var elem = event.currentTarget;
elem.append('<div>test</div>’); //Appending is failing
});
}
}]);
TypeError: 'undefined' is not a function (evaluating 'elem.append('<div>test</div>')')
I am just starting off with AngularJS and stuck with the above issue, I am trying to append a div to the container.
Try with this
containers.bind('click', function (event) {
var elem = event.currentTarget;
$(elem).append('<div>test</div>’); //Appending should work
}
as elem can be the HTML input object you have to convert it into jQuery object to use .append() method of jQuery! so wrap your elem variable arround $(). It should work
Better to use this. Removes dependency to JQuery as Angular core only use JQLite. It is basically the same thing that happens.
https://docs.angularjs.org/api/ng/function/angular.element
containers.bind('click', function (event) {
var elem = event.currentTarget;
angular.element(elem).append('<div>test</div>’); //Appending should work
}

Why is jQuery .click() is skipped over?

I have a small script of javascript which iterates over a set of checkboxes which grabs the name attribute and value and then convert it to json. Then I use that value to set the href of an element and then try to trigger a click.
For some reason everything seems to function properly except for the click. I successfully change the href, I console.log() a value before the .click() and after. Everything hits except for the click. The url in the href is value as I clicked it manually.
I have my script included just before the closing body tag and have it wrapped in $(document).ready(). and I do not have duplicate ID's (I viewed the rendered source to check)
Can anyone offer some insight on this?
Here is the javascript
$(document).ready(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var i = 0;
var list = new Array();
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var id = $(this).val();
list[i] = new Array(name, id);
i++;
});
var serList = JSON.stringify(list);
console.log(serList);
var webRoot = $("#webRoot").text();
$("#exportLink").attr('href', webRoot+"/admin/admin_export_multiExport.php?emailList="+serList); //hits
console.log('1'); //hits
$("#exportLink").click(); //this line never executes
console.log('2'); //hits
});
});
$(selector).click() won't actually follow the link the way clicking on it with your mouse will. If that's what you want, you should unwrap the jquery object from the element.
$(selector)[0].click();
Otherwise, all you're doing is triggering event handlers that may or may not exist.
I may guess you need
$(document).on('click', '#multiExport', function(e){
(you can replace document by a nearest element, if you got one).
if you need dynamic click event binding.
EDIT
I would try something like that :
$(document).ready(function() {
$("#exportLink").click(function() {
window.location = $(this).attr('href');
});
$("#multiExport" ).on('click', function(e){
//whatever you want
$('#exportLink').attr('href', 'something').trigger('click');
});
});
$("#exportLink").click(); // this would launch the event.
I must admit I am very surprised that the .click() does not work.
If the idea is to load the page, then the alternative is
$(function() {
$("#multiExport" ).on('click', function(e){
e.preventDefault();
var list = [];
$('.appSelect:checked').each(function(){
var name = $(this).attr('name');
var val = $(this).val();
list.push([name, val]);
});
var serList = JSON.stringify(list);
var webRoot = $("#webRoot").text();
location=webRoot+"/admin/admin_export_multiExport.php?emailList="+serList;
});
});

jQuery click dynamic element

See the code's comment:
$.each($('input[type="radio"]'), function(){
var input = $(this);
var container = $('<div class="radio"></div>');
var mark = $('<span />');
input.wrap(container).after(mark);
container.click(function(){
alert('test'); // Not triggered.
});
});
The html is:
<input type="radio" value="female" name="gender" />
Anyone know why the alert is not triggered when clicked, and yes it is visible in CSS. When I use :
console.log(container);
It does give me the HTML it is containing.
Thanks
$('body').on('click', 'div.radio', function() {
});
Full Code
$('body').on('click', 'div.radio', function() {
alert('test');
});
$.each($('input[type="radio"]'), function(){
var input = $(this);
var container = $('<div class="radio"></div>');
var mark = $('<span />');
input.wrap(container).after(mark);
});
NOTE
Instead of body, you should use a static-element that is the container of container.
Why you need this
You need delegate event handler, as your element added to DOM dynamically that means. after page load.
after some tested it seems to me that the "wrap" clone the object you pass it as argument, or reference to the object is lost but I'm not so sure.
a first solution is to assign the event "onclick" before moving the object in the "wrap".
$.each($('input[type="radio"]'), function(){
var input = $(this);
var container = $('<div class="radio"></div>');
var mark = $('<span />');
$(container).click(function(){
alert('test'); // triggered now.
});
input.wrap(container).after(mark);
});
a simplified version :
$.each($('input[type="radio"]'), function(){
var wrapper = $('<div class="radio"></div>').click(function(){
alert('test'); // triggered now.
});
$(this).wrap(wrapper).after($('<span />'));
});
dont forget to decalare this function in the onload function
$(function(){
// your code here ....
});
I was also affected by this and found that on is available only with jquery 1.7 and above.
I am on jquery 1.4.1 and on is not available with version. Upgrading jquery was something I wanted to avoid.
Thankfully delegate was there and it solved the problem.

trying to append content to DOM element

I'm trying to add a div to a row of content with the click of a button. My code works for the first row but not for any other row. Please help. This is the function for the button:
$(".addMMbtn").each(function() {
$(this).bind("click",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
}
);
});
You can see a fiddle of the problem here: http://jsfiddle.net/z7uuJ/
$(".addMMbtn") will only find the elements present on the page and your code will only attach click event handler on them. Since you are adding the elements dynamically you should either use delegate or on (if you are using jQuery 1.7+) for click event to work on them too. Try this
Using delegate
$('#default').delegate('.addMMbtn', 'click', function() {
$('<div class = "mmCell prep"></div>')
.appendTo($(this).closest(".txtContentRow").find(".txtContent"));
});
Using on
$('#default').on('click', '.addMMbtn', function() {
$('<div class = "mmCell prep"></div>')
.appendTo($(this).closest(".txtContentRow").find(".txtContent"));
});
Demo
Instead of assigning click event directly on the button you need to use on():
$(document).on("click", ".addMMbtn",
function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
}
);
In this case event handler will be subscribed to all newly added elements.
Code: http://jsfiddle.net/z7uuJ/5/
You don't need to loop through the elements to bind the handler:
$(".addMMbtn").live('click', function() {
var thisRow = $(this).closest(".txtContentRow");
var thisTxt = thisRow.find(".txtContent");
var cellStr = '<div class = "mmCell prep"></div>';
$(cellStr).appendTo(thisTxt);
});

Categories