onclick event on Ajax output - javascript

Hi i am using Ajax to get a SELECT tag. I mean, if i click on a button it will generate a SELECT tag inside HTML, i have different outputs for different options of select.
I need an onclick event on that SELECT tag, i tried using JQuery
$('#id').click(function() {
alert('test');
});
Its not working. Can anybody help, please

Because the select tag is dynamically added to the HTML after the event was set, the event is not set on the select tag.
A simple solution is to use live() here:
$('#id').live('click', function() {
alert('test');
});

as you are dynically generating html use live instead of click
$('#id').live('click', function() {
// Live handler called.
});

Make sure
you have jQuery script file is inserted in your html page,
you have assigned id id to one and only one item on your page,
you give us a link to see your page if nothing else helps. :)

live is now deprecated. Use on instead.

Related

access and click buttons without ID or class tag

how do i click the button(LayersWidget) in the below html code which doesnt have id or classname.
code is provided below screenshot with highlighted in red.
as i am unable to find the id, i cannot click it using Javascript code
So in your case, the element does have a class, but you could also select the element by another attribute such as the data-dojo-attach-point attribute:
$('li[data-dojo-attach-point="LayersWidget"]')
i am able to access the element using the code
var elmnt1 = document.querySelector('[title="Table of Contents"]');
You can try to select it using jquery and the data attribute as the selector
$('[data-dojo-attach-point="LayersWidget"]').on('click', function() {});
i use the below code to click the element which i got from one of the answer from above.
$('li[data-dojo-attach-point="LayersWidget"]').click();

Bind onclickevent for a dynamically added jQuery element

Could you please advise how to bind a onclick function for a dymanically added iframe element in JQuery.
The situation is like - I have got 4 radio buttons. Whenever somebody is selecting the second radio button I am loading one iframe and there is a button in that iframe where I need to have one onclick function from an external JS file.
on page load $("#iframe").length = 0, so could not use the $("#iframe").find method.
Please advise
Thanks,
Aniket
Find the iFrame with a valid selector and use .contents() to get its content.
var iframe = $('#your_iframe').contents();
iframe.find('your_clicable_item').click(function(event){
console.log('work fine');
});

Using jQuery to select checkboxes with click events

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
});

How to work with dynamically created fields?

I have web layout, which can contains several links on it. Those links are dynamically created, using AJAX functions. And it works ok.
But, I don't know how can I work with those "dynamically created links" (ie. how to call some JS or jQuery function if I click on them). I guess that browser can not recognize them, since there are created after page is loaded.
Is there some function, that can "re-render" my page and elements on it?
Tnx in adv on your help!
You can use the 2 following methods jQuery provides:
The first one, is the .live() method, and the other is the .delegate() method.
The usage of the first one is very simple:
$(document).ready(function() {
$("#dynamicElement").live("click", function() {
//do something
});
}
As you can see, the first argument is the event you want to bind, and the second is a function which handles the event. The way this works is not exactly like a "re-rendering". The common way to do this ( $("#dynamicElement").click(...) or $("#dynamicElement").bind("click", ...) ) works by attaching the event handler of a determinate event to the DOM Element when the DOM has properly loaded ($(document).ready(...) ). Now, obviously, this won't work with dynamically generated elements, because they're not present when the DOM first loads.
The way .live() works is, instead of attaching the vent handler to the DOM Element itself, it attaches it with the document element, taking advantage of the bubbling-up property of JS & DOM (When you click the dynamically generated element and no event handler is attached, it keeps looking to the top until it finds one).
Sounds pretty neat, right? But there's a little technical issue with this method, as I said, it attaches the event handler to the top of the DOM, so when you click the element, your browser has to transverse all over the DOM tree, until it finds the proper event handler. Process which is very inefficient, by the way. And here's where appears the .delegate() method.
Let's assume the following HTML estructure:
<html>
<head>
...
</head>
<body>
<div id="links-container">
<!-- Here's where the dynamically generated content will be -->
</div>
</body>
</html>
So, with the .delegate() method, instead of binding the event handler to the top of the DOM, you just could attach it to a parent DOM Element. A DOM Element you're sure it's going to be somewhere up of the dynamically generated content in the DOM Tree. The closer to them, the better this will work. So, this should do the magic:
$(document).ready(function() {
$("#links-container").delegate("#dynamicElement", "click", function() {
//do something
});
}
This was kind of a long answer, but I like to explain the theory behind it haha.
EDIT: You should correct your markup, it's invalid because: 1) The anchors does not allow the use of a value attribute, and 2) You can't have 2 or more tags with the same ID. Try this:
<a class="removeLineItem" id="delete-1">Delete</a>
<a class="removeLineItem" id="delete-2">Delete</a>
<a class="removeLineItem" id="delete-3">Delete</a>
And to determine which one of the anchors was clicked
$(document).ready(function() {
$("#links-container").delegate(".removeLineItem", "click", function() {
var anchorClicked = $(this).attr("id"),
valueClicked = anchorClicked.split("-")[1];
});
}
With that code, you will have stored in the anchorClicked variable the id of the link clicked, and in the valueClicked the number associated to the anchor.
In your page initialization code, you can set up handlers like this:
$(function() {
$('#myForm input.needsHandler').live('click', function(ev) {
// .. handle the click event
});
});
You just need to be able to identify the input elements by class or something.
How are these links dynamically created? You can use use the correct selector, given that they are using the same class name or resides in the same tag, etc.
consider the html form
<form>
<input type="text" id="id" name="id"/>
<input type="button" id="check" name="check value="check"/>
</form>
jquery script
$('#check).click(function() {
if($('#id).val() == '') {
alert('load the data!!!!);
}
});
here on clicking the button the script check the value of the textbox id to be null. if its null it will return an alert message....
i thin this is the solution you are looking for.....
have a nice day..
Noramlly , the browser process response HTML and add it to DOM tree , but sometimes , current defined events just not work , simply reinitialize the event when u call the ajax request ..
All you need to do to work with dynamically created elements is create identifiers you can locate them with. Try the following code in console of Firebug or the developer tools for Chrome or IE.
$(".everyonelovesstackoverflow").html('<a id="l1" href="http://www.google.com">google</a> <a id="l2" href="http://www.yahoo.com">yahoo</a>');
$("#l1").click(function(){alert("google");});
$("#l2").click(function(){alert("yahoo");});
You should now have two links where the ad normally is that were dynamically created, and than had an onclick handler added to bring up an alert (I didn't block default behaviour, so it will cause you to leave the page.)
jQuery's .live will allow you to automatically add handlers to newly created element.
If your links are coming in via AJAX, you can set the onclick attributes on the server. Just output the links into the AJAX like this:
Holy crap I'm a link
The return false makes sure the link doesn't reload the page.
Hope this helps!

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