Binding jQuery .on event to dynamic button with dynamic id - javascript

I have a situation where I need to bind an onclick event to a button which is being dynamically injected into the main html document by an external JavaScript.
The problem is that that the class id of the button is suffixed with some dynamic numbers which change every time the page is reloaded.
Please see example:
<button class="clickme12345" type=submit value=clickme>send</button>
Now the situation is that on every page reload the numbers for the class id for the button will change so next time it will be clickme67890.
Would there be any way to get the jQuery binding to work for this situation?
Any reply would be greatly appreciated.

If this is really how you want to use it, you could use an attribute selector
Something like [attr*=value] where the attr contains the string value.
For example (in jQuery):
var $btnElement = $('[class*="clickme"]');
The above will select any elements that have a class attribute containing clickme

Related

Add id to dynamically created DIV

I would like to add an ID to the div with the class name="leaflet-control-layers-base". Because this HTML script is automatically generated through an API (Leaflet) when the page is loaded, I cannot add the id within the script.
The reason I am asking is because I have two of these scripts as shown below within my page. I would like to distinct them from each other so that I can refer to them individually. The only difference is that the other script is not located in the "TOCContent" div.
Any ideas how I can add an id using JavaScript or jQuery to the 'leaflet-control-layers-base' class?
Here is my script:
<div id="TOCContent">
<div class="leaflet-control-layers leaflet-control-layers-expanded" aria-haspopup="true">
<form class="leaflet-control-layers-list">
<div class="leaflet-control-layers-base">
</form>
</div>
Try this:
$(".leaflet-control-layers-base").attr("id","your id will go here");
Select the element using the combinator selector, to ensure it selects a descendant of #TOCContent, then set the id property.
$('#TOCContent .leaflet-control-layers-base').prop('id', 'someid');
Remember to run this after your API code has rendered the elements on the page, not before. You will probably need to hook up to some sort of complete event on your API, because the basic DOM Ready event will likely fire before the API has rendered the elements.
Side note: it may not be necessary to give the element an ID, since by doing so you need to obtain a reference to the element anyway, which you can store in a variable.
var base = $('#TOCContent .leaflet-control-layers-base');

How to click a save as html link with changing ID's?

I know how to click a link using javascript,
document.getElementById('yourLinkID').click();
But what if your ID is always changing or you are not sure what your ID is going to be? I have a html link that auto generate from a grid of data into a excel file that once i click on will give me a link "CLICK" and then it will save to your file. Any idea's or any other way of click a html link?
Here is an example html:
Click
You can use class for that kind of button, but when you slect $('.class-name') it you can cause clicking on multiple links.
Other solution is to traverse DOM (ie. using jQuery)
https://api.jquery.com/category/traversing/tree-traversal/
You can use this function to move between your elements:
$( "li" )
.closest( "ul" )
If you have only one elemement like this you can use querySelector function:
document.querySelector('[id^=myIdIsAlwaysChanging]').click();
if you have more then one element you will need to use document.querySelectorAll and iterate over the list.

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/

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