I dynamically load a div on page Leagues.php with a button like this:
$("#leaguesSelectionTable th").click(function(){
var leagueSelect = $(this).attr('id');
if ($('#leaguesTable').length){
$("#loadLeagueTables").empty();
$("#loadLeagueTables").load("php/leagueTable.php?leagueSelect="+encodeURIComponent(leagueSelect));
}
else {
$("#loadLeagueTables").load("php/leagueTable.php?leagueSelect="+encodeURIComponent(leagueSelect));
}
});
This loads a table based on which button I pressed, using leagueTable.php to handle all of that. Once that table is loaded, (a bunch of leagues) I want to then be able to click on a row from this table and following the same logic, display the team table.
$("#assoc_league tr").click(function(){
var teamSelect = $(this).attr('id');
if ($('#teamsTable').length){
$("#loadTeamTables").empty();
$("#loadTeamTables").load("php/teamTable.php?teamSelect="+encodeURIComponent(teamSelect));
}
else {
$("#loadTeamTables").load("php/teamTable.php?teamSelect="+encodeURIComponent(teamSelect));
}
});
I think the problem is that since table #assoc_league is not yet present, this does not work. I tried an alert and don't get any response. This jQuery is in the same file attached to Leagues.php. Any ideas how to approach this?
Thanks.
Since your table has been added dynamically to the DOM, all the events for this table and child elements inside it will not be avaliable. In this case, you need to use event delegation :
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all children matching a selector,
whether those children exist now or are added in the future.
$('#loadLeagueTables').on('click', '#assoc_league tr', function() {
// Your code here
});
Related
I have jQuery drop down accordions on each post in my loop, and I want to trigger them individually on click. They work by checking div classes, so I've made sure that each class is dynamically named based on the post-ID. I've also created a variable to generate the name of class used in the script...
This is my code:
<script type="text/javascript">
var post_ID = ".show-dts.<?php the_ID();?>";
$(post_ID).click(function() {
if($('.show-more-dts').css('height') != '1px'){
$('.show-more-dts').stop().animate({height: '1px'}, 200);
$(this).text('Show details');
}else{
$('.show-more-dts').css({height:'100%'});
var xx = $('.show-more-dts').height();
$('.show-more-dts').css({height:'1px'});
$('.show-more-dts').stop().animate({height: xx}, 400);
// ^^ The above is beacuse you can't animate css to 100% (or any percentage). So I change it to 100%, get the value, change it back, then animate it to the value. If you don't want animation, you can ditch all of it and just leave: $('.show-more-snippet').css({height:'100%'});^^ //
$(this).text('Hide Details');
}return false;
}); </script>
Checking the page source, I can see that the jQuery code is creating the correct class names using the variable, but I'm not quite there, because when any of the accordions are clicked, all them are triggered together still.
Will try to keep this simple so its not too much reading
I have a simple page with the following ...
$divid = 'append_here_$x;
$clickme = 'click_$x';
<div id='$clickme'>Click Me</div>
<div id='$divid'></div>
Then , I have a separate php file that builds content in a while loop generating a unique id for each div.
while ...
$imgid = 'imgid_$z' ...
<div id='$imgid'>This was appended</div>
Finally, I have this just for testing and keeping things short
$( "[id^='imgid_']").on( "click", function() {
alert('you clicked me');
});
This above works fine for the most part. If you were to click on click me, it will do ajax call and a post against the file with the while loop in it, return data and append it inside the append_here_ div. The problem is the new appended data that also has an id so yo can click will not respond to the simple click.
The way you link the click event to the elements of the page will not work for elements added later.
You are linking the event to the elements present by the time you define the click events, but if you add items later, they won't have the event on them. You could do:
$(document).on('click', '[id^="imgid_"]', function() {
alert('you clicked me');
});
That way, the event will be on the document, which is present at the startup, and everytime you click, it will check the selector (second parameter), so the new elements will respond to the click.
I have external file which generate the checkbox list. And this file was load through jquery load. I want the checkbox click and update its parent div with something.
html
<div id="testiContent"></div>
checkbox.php
<div class="alert alert-info"><input type='checkbox' class='groupid' value='1'>1</div>
<div class="alert alert-info"><input type='checkbox' class='groupid' value='2'>2</div>
<div class="alert alert-info"><input type='checkbox' class='groupid' value='3'>3</div>
jquery
$('#testiContent').load('checkbox.php');//load file via ajax
$("#testiContent input.groupid").change(function(){
if($(this).is(":checked")){
$(this).parents().addClass("alert alert-success");
}else{
$(this).parent().removeClass("alert alert-success");
}
});
Ideally, when the checkbox click, then the alert div will change into green. I can make it working on the normal scrip but not a chance with ajax.
Fiddle here : http://jsfiddle.net/o6Lk17db/1/
My hunch is that you are simply attaching the change listener before the content is loaded in the DOM, so it doesn't actually target anything. You could pass a callback function to load only attempt to attach the change listener after the content is in the DOM, but it might be easier to just use the on method on the document-- that way it is evergreen and doesn't need to rely on callbacks:
$('#testiContent').load('checkbox.php');//load file via ajax
$(document).on('change', 'input.groupid', function(e){
var target = e.target;
if($(target).is(":checked")){
$(target).parents().addClass("alert alert-success");
}else{
$(target).parent().removeClass("alert alert-success");
}
});
That may not be exactly right but I think it will at least trigger.
You can't bind to an element that isn't there yet, so your dynamically added ones aren't subject to the $"#testiContent input.groupid" selector. The way around this is to bind to something that is already present. For example, the parent container where your elements are dynamically being added.
Try something like this:
$("#testiContent").on('change', 'input', function(){ ... });
will attach a listener to the parent, specifically for events on the appropriate (input) targets within that parent.
When html controls are loaded dynamically, events for these controls needs to be bind manually. So you need to bind check/click events once element adding is done. You can write code as
$(document).on("change","input.groupid").change(function(){
// your code here
});
use this
$("input.groupid").change(function() {
if ($(this).is(":checked")) {
alert($("input.groupid").val());
$(this).closest('div').removeClass("alert-info");
$(this).closest('div').addClass("alert-success");
} else {
$(this).closest('div').removeClass("alert-success");
$(this).closest('div').addClass("alert-info");
}
});
You need to use change event on document because the content is loaded via ajax. and you can use toggleclass function for change the parent div.
$('#testiContent').load('checkbox.php');//load file via ajax
$(document).on('change', '.groupid', function(e) {
$(this).closest("div").toggleClass("alert-success alert-info");
});
I'm somewhat new to jQuery, and I see examples of how to add clickable dynamic TRs to existing tables, but how can I add an entirely new table dynamically that has clickable TRs?
My HTML code:
<input type="text" id="containing"><div id="results"></div>
My jQuery code, which POSTs the input and returns the new HTML table into the Results div:
$("#containing").on("keyup", function()
{
$.post("http://URL.com/search.php", { searcher: $(this).val() },function(data, textStatus)
{
$("#results").html(data);
});
});
Search.php returns the following format:
<table id="resultantTable"><tr><td></td></tr></table>
... and additional jQuery code that's supposed to let me click the new table rows, which doesn't work:
$(document).ready(function()
{
$("#resultantTable").on('click','tr',function()
{
var href = $(this).find("a").attr("href");
if(href)
{
window.location = href;
}
});
});
This jQuery code works for tables that load up with the document, but I cannot get the TRs to be clickable in the dynamically-created table that is returned from search.php.
Any ideas?
You need to add the listener on a parent. example:
$(document).on('click', '#resultantTable tr', function(e){
//ToDo...
});
This behaviour happens because you set the event listener on all existing table, but when you dynamically create a table it does not have this listener.
One way to fix this is to set the event listener on the newly created table on creation, but the way I do it is putting the event listener on a parent element which I know exists on document load (like body)
$('body').on({
click: function(){
...
}
}, '#resultantTable tr' )
This happens because the events was registered before the ajax content exist. (resultantTable does not exists the first time the DOM is loaded)
Try to add your function after $("#results").html(data);
it is a good practice, in your ajax call, that you listen on success/error events
Add the render and click jobs inside the success events.
See jquery documentation about that
Simply what I want is to to change the button class and value in order to change the button functionality.
what happening is that the value and the class are changed successfully BUT the functionality remain the same as for the old class
why?!
does the browser store the jquery code somewhere and load from it?! and how can i refresh it in that case??
here's piece of my code:
(I'm using Jquery Ajax with html and php)
var target_button; // global variable to store the target button
$(".activateButton").click(function(){
var serial_number = $(target_button).attr("id");
var cvc = $("#cvc").val();
$.ajax({
type: "GET",
url: '../ajax/tag.php',
data:
{
s: serial_number,
c: cvc
}
}).done(function(data)
{
var result = jQuery.parseJSON(data);
if (result == "1")
{
$("#message").text('Tag Successfully Activated');
$("#overlay_form").fadeOut(500);
$(target_button).attr("value", "Disable");
$(target_button).removeClass("popActivateButton"); //<---------- REPLACING THE CLASS
$(target_button).addClass("enableDisableButton"); //<----------
}
here's the buttons:
if($tags[$i]['Status'] == 1){
$button = "<input type=\"button\" class=\"enableDisableButton\" id=\"".$tags[$i]['SerialNumber']."\" value=\"Disable\"/>";
}
if($tags[$i]['Status'] == 2){
$button = "<input type=\"button\" class=\"popActivateButton\" id=\"".$tags[$i]['SerialNumber']."\" value=\"Activate\"/>";
}
When you use a selector it selects all elements that match at the time you execute the code. Previously called selectors - even if cached - do not dynamically update when new elements that match them are added to the page.
If you've bound event handlers to elements, then they're going to stay there until you a. remove the event handler(s), or b. remove the element entirely. Just changing the class isn't going to magically change the event handlers that are bound.
I'd suggest using event delegation instead:
$(document).on('click', '.enableDisableButton', function() {
//your code for enableDisableButton
}).on('click', '.popActivateButton', function() {
// your code for popActivateButton
});
With event delegation the selector is checked when the event is triggered, rather than when the code executes, so it will reflect changes to the page.
Note that I've used document in the code example above. However, you should instead use a selector for a static element (one that won't be removed) that will contain the elements you want to execute the event handler function for; the closer it is in the DOM structure to the dynamic elements the better.
Yes once event assigned you need to clear those previous events and bind new events to each.
suppose you have button and you have assigned click event now unfortunately you want to clear click event and something else you can do it as below,
$(SOMESELECTOR).unbind('previous_event').bind('new_event');.
For more search for jQuery bind and unBind.