.on('click') with wildcard not not delegating as expected - php

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.

Related

jQuery Add Dynamic Table with Clickable Rows

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

how to load php page in a div using jquery

Imagine that I have two divs , left div and right div ,
In the left div I have some button. When I click on the home button the page home.php loaded in the right div, I use load() function to do this and when I click on about button the page about.php loaded in the right div .
My problem is that I have some other buttons in that page (I mean about.php). When I click on it some other pages must load in the right div.
I mean when I click on about button in the left div, about.php loaded in the right div.
I don't have a problem doing this it's work fine , but the problem is when i click on a button in about.php, I want about.php to be hide and load x.php in his place (right div).
This is the code that I have :
$('#about').click(function () {
$('#rightdiv').load('about.php', function() {
$('#about_button').click(function () {
$('#rightdiv').load('x.php');
})
})
})
First of all, you shouldn't nest your click handlers like you have done - they should be separate. Second, when you load the about.php jQuery is unaware of the new stuff that you have placed in the DOM. To fix that you use event delegation, meaning the click event from about.php will bubble up to an element that already existed at the time the page was loaded. jQuery is aware of that element and will handle the event properly.
$('#about').click(function () {
$('#rightdiv').load('about.php');
});
// 'click' event delegated to 'body'
$('body').on('click', '#about_button', function () { // #about_button is in about.php
$('#rightdiv').load('x.php');
})
Instead of binding the event to the items on load, you tell the browser to check ther a.nav's which occur in the document.
<a class="nav" href="about.php">about.php</a>
<a class="nav" href="other.php">other.php</a>
<a class="nav" href="last.php">last.php</a>
$(document).on('click', 'a.nav',function (e) {
e.preventDefault();
var page = this.href;
$('#rightdiv').load(page);
})
It's better to make the first selecttor ( $(document) ) as close to the actual elements, and highly recommended you use an ID:
$('#rightdiv').on('click', 'a.nav',function (e) {});
In this snippet, all a.nav in #rightdiv will get triggered, initial load or dynamicly.
you have to bind all click events after you load that php page, so create a function, that will do it after every .load call

jQuery.click on a div that hasn't yet loaded

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

using jquery variable in php

I've got a dynamic table filled by a recordset from MYSQL.
Each row has it's own delete button (image) to delete the specific row.
This button has a class="button".
I'm using a JQuery popup modal to get a popup when a delete button is clicked.
In this JQuery script i'm creating a variable which contains the numeric value of the first td cel of the row that has been clicked on.
This all works perfectly.
What i'm trying to accomplish is to use this variable on the same php page.
Here is where my knowledge runs out.
I've read some examples where Ajax is the solution for this, but i lack the knowledge to use these examples for this solution.
JQuery code:
<script src="../javascript/jquery-1.8.2.js"></script>
<script src="../javascript/jquery.reveal.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.button').click(function(e) { // Button which will activate our modal
var value=$(this).closest('tr').children('td:first').text();
alert(value); // this works
$('#modal').reveal({ // The item which will be opened with reveal
animation: 'fade', // fade, fadeAndPop, none
animationspeed: 500, // how fast animtions are
closeonbackgroundclick: false, // if you click background will modal close?
dismissmodalclass: 'close' // the class of a button or element that will close an open modal
});
return false;
});
});
</script>
I've been trying too much that i don't see the logic anymore.
I hope that someone can help me with this.
The issue is that your JavaScript runs in the client -- the user's web browser -- while your PHP runs on your server. It's a two-stage process: first, all the PHP is executed on the server and the HTML is rendered, which is then sent to the client (the browser). Then, the client executes all the JavaScript on the page.
You need some way to communicate the JS variable (value) to your server if you want to be able to use it in your PHP code. AJAX is one such way, but it would be helpful to have more information on how exactly you want to use this information in your PHP.
Edit: based on your comments above, something like this should work. You'll have to give your Yes button an id attribute (here I'm assuming the id is yesButton).
$(.button).click(function() {
var value=$(this).closest('tr').children('td:first').text();
$("#yesButton").attr("href", "delete_verlof.php?id=" + value);
$('#modal').reveal({ // The item which will be opened with reveal
animation: 'fade', // fade, fadeAndPop, none
animationspeed: 500, // how fast animtions are
closeonbackgroundclick: false, // if you click background will modal close?
dismissmodalclass: 'close' // the class of a button or element that will close an open modal
});
return false;
});
The important thing to note is that the JS variable does not exist yet at the time at which your PHP executes, so it is not available to the PHP. What I've done here instead is to dynamically change the href of the Yes button whenever the user clicks a td, which should have the desired effect.
If your using this in a form, then you could create a hidden input field with a unique id and add it with.
$('#idOfField').val(value);
And then use php to get the element from wherever you put it in your code.
Other then you might find attr usefull. For an example
$('#idOfField').attr('data-id', value);
Where the ID can be an div, span, i, a, bold, strong etc etc etc.

How to trigger click on ajaxSubmitButton

I have filter-from with ajaxSubmitButton.
CHtml::ajaxSubmitButton('Show',Yii::app()->createUrl('office/ajaxFilter'),array('update'=>'#office-install'),array('id'=>'filterSubmit'))
And i want to submit it on pageLoad (to recive data using default filter values). How to trigger click on ajaxSubmitButton?
using
$(document).ready(function () {
$('#filterSubmit').trigger('click');
}
raise redirect.
If I understand your problem correctly, you need to trigger the click on #filterSubmit element to run some actions associated with it, but without having the page following the regular click, if so:
UPDATE YOUR CODE TO THIS:
$(document).ready(function () {
// bind a click event to the button
$('#filterSubmit').bind('click', function(e) {
// the browser from following the click
e.preventDefault();
});
// trigger the click on the button
$('#filterSubmit').trigger('click');
// unbind the click event to allow the normal usage of that button
$('#filterSubmit').unbind('click');
}
This assumes that you have some click events binded to the #filterSubmit... If that is not the case, perhaps a more elaborated question cold allow us to help you out!
EDITED
By the comment you've just post, you can do something like:
YOU CODE (with a minor fix):
$(document).ready(function(){
$('#filterSubmit').trigger('click');
}); // was missing ); here
WITH Yii Framework
<?php
// the script string
$ourscript = "$('#filterSubmit').trigger('click');";
// Yii’s registerScript
Yii::app()->clientScript->registerScript(
'filtersubmitclickscript',
$ourscript,
CClientScript::POS_READY
);
?>
This topic has been covered many times here:
https://stackoverflow.com/search?q=click+trigger+jquery
You might get issues in several browsers with the trigger because of security restrictions.

Categories