JQuery does not determine the div class which is printed from ajax - javascript

I have html elements that printed in html page using smarty engine , then printed from jquery
the html which is printed from smarty is
<div id="broadcastsXXX" class="broadcast orginal-broadcast highlightedbroadcast">
<i class="dogears"></i>
<div class="content">
...
...
</div>
</div>
and the html which is printed from jquery is the same html code which is printed comming from smarty template as shown above.
I want to remove the css class "highlightedbroadcast" when someone clicked on the div which has the class "content" as shown above
so I do the jquery code:
$(document).ready(function() {
$('.content').click(function() {
$(this).parent().removeClass("highlightedbroadcast");
var broadcastid = ($(this).parent().attr("id"));
});
});
The function is changing the clicked div parent and remove the class highlightedbroadcast.
when the user clicked on the .content div that is printed from smarty template when page loas its remove the highlightedbroadcast css class without any problem. but if the user clicked on the div .content which has been printed from ajax it will not remove the class and do nothing.
I try to add alert('hi') to the function and it also says hi when the user clicked on the .content div which is comes from smarty and do noting when the user clicked on the div which is printed from ajax.
note that the broadcastsXXX is dynamic as broadcasts123 broadcasts124 .. etc
and this is a real example http://jsfiddle.net/samshannaq/FUK5Z/2/
so is there any solution for this?

.click() will only add event handlers to the current DOM.
If you want jQuery events to also apply to any HTML that is subsequently loaded via AJAX, you need to use the .on() event handler rather than .click():
$(document).ready(function() {
$('body').on('click', '.content', function() {
$(this).parent().removeClass("highlightedbroadcast");
var broadcastid = ($(this).parent().attr("id"));
});
});
Either that, or you need to add the click events to HTML that is loaded via AJAX after every AJAX call.

I think you should use 'live', while not just 'bind' or 'click' . When document is ready, the div.content is not rendered at all ( they are rendered through ajax response. ). so change your code to
$(document).ready(function() {
$('.content').live('click',function() {
$(this).parent().removeClass("highlightedbroadcast");
var broadcastid = ($(this).parent().attr("id"));
});
});
may work.

Related

jQuery does not recognize PHP generated child element when clicked

I am working on a website on which I have to display buttons based on database content. Clicking these buttons should then send a request to the database and reload the content of the page appropriately.
Everything is done with Ajax and jQuery by executing PHP scripts.
I can generate the buttons, but jQuery does not trigger when they are clicked.
It seems that jQuery detects a click on the div containing the buttons but not on the buttons themselves.
I was told that it may be because the jQuery script is loaded before the page is updated with the new HTML content.
This is the div container for all the choice buttons:
<div id = "choices">
<!-- Choices button will be displayed here -->
</div>
Here's the PHP code creating the HTML for the buttons:
echo " <button class = 'choice' id = \"$id\">
$content
</button> ";
This code is loaded in the previous #choices div by this jQuery code :
$.post("php_script/getChoices.php",
function(result){
$("#choices").html(result);
});
Pretty basic, and the expected (and actual) output on the webpage is :
<div id = "choices">
<button class = 'choice' id = "1">
Yes.
</button>
<button class = 'choice' id = "2">
No.
</button>
</div>
But when I write this :
$(".choice").click(function());
It never triggers, no matter how basic the function.
However, having another event to interact with the buttons is possible.
For example, the code below does hide the buttons when the #choices div is clicked.
$("#choices").click(function(){
$(".choice").hide();
});
In order to understand the problem, I wrote this jQuery script that print the content of the element that was clicked on the console.
$("*").on('click', function(event){
event.stopPropagation();
console.log('Clicked: ' + $(this).html());
});
And when I click on a button, it always returns the whole #choices div instead of just the content of the button.
As I said, I think this is because I am trying to interact with HTML elements that were added after the jQuery script was loaded (it is written in the section of my page).
Is my assumption correct and what should I do in order to trigger an action when the button themselves are clicked ?
You can always target the document to trigger dynamically created elements:
$(document).on('click', '.choice', function (e) {
e.preventDefault(); //stop default behaviour
var id = this.id; //get element ID
$(this).hide(); //hide element
});
As mentioned you can use event delegation
$(function(){
$("#choices").on("click", "button", function(){
alert("clicked");
});
});
Or manually bind the event handler when you add the new buttons
// called each time new buttons are added
function bindOnClick(){
$("#choices").off();
$("#choices").on("click", "button", function(){
alert("clicked");
});
}
$(function(){
// called once when dom is ready
bindOnClick();
});
If you don't call off you will bind the onclick event to the same element more than once.

Loading several .php file into one div

Hello i have this code to load php file into div. Its working but i need load next file into this div.
<script type="text/javascript">
$(function() {
$("a.load").on("click", function(load) {
load.preventDefault();
$("#zaw").hide().load(this.href).fadeToggle(1000);
});
});
</script>
<li><a class="load" href="zzz.php">zzz</a></li>
If i click "zzz" link loading file into my div (file table with images) i need hide this page and load next by click image.
UPDATE
Now working
<script type="text/javascript">
$(function() {
$("a.load").on("click", function(load) {
load.preventDefault();
$("#zaw").hide().empty().load(this.href).fadeToggle(1000);
});
});
</script>
You just simply need to bind another click event to an image (or table body) that you load through load() function. However, you may experience some issue with your click not working, and heres why:
If you attach two click handlers, one for a.load and second for, let's say, .image than only the first event will actually get bind to its element, and the socond one won't be attached because, well, .image doesn't exist yet - not untill you load it.
You could expect, that once you php file content will get loaded (with .image elements in it), then clicking them will fire an action you have declared, but it won't - those .image's are new DOM elements and they missed an event binding procedure which was done only once when the DOM was created (or DOM was ready if you use $.(document).ready()).
So, in order to get those clicks to work you need to either attatch them on load() function callback, like so:
$("a.load").on("click", function(load) {
load.preventDefault();
$("#zaw").hide().load(this.href, function(){
$(".image").on("click", function(e) {
$("#zaw").hide().load(/* load what you want */);
});
})
.fadeToggle(1000);
});
or insert .image click event binding inside php file you are loading or use some sort of delegation, for example:
$(document).on('click', '.image', function(){
/* do what you want */
});
which will make sure that even new, dynamically created DOM element will fire an action you want.

Hover only works when user clicks on the element

Following is the link to my js fiddle in which i am trying to show a popover on hover property of the element hover for popover with id a1 . The problem i am facing is that when the page loads for the first time and on hover on that element the popover doesnot display. But when user clicks on hover for popover and then do the hover, then hover property works perfectly fine kindly let me know why isn't it happening on the page load event and how can i fix it so user doesnot have to click on the button and it display whatever in it.
Note: It can be easily done by following but the problem is ids for the elements are being dynamically generated so i cannot use the following method for specifically one id.
$(function ()
{ $("#example").popover();
});
JSFIDDLE:
http://jsfiddle.net/weuWk/323/
First, add a class to all of your hover elements:
<span id="a1" class="btn large primary hoverable">Popover</span>
Then, add the popover to each item:
$(document).ready(function(){
$('.hoverable').popover({title: "Hello"});
});
Edit: To reference the id (or any other attribute), you can use .attr() as follows:
$(document).ready(function(){
$('.hoverable').each(function(){
$(this).popover({title: $(this).attr('id')});
});
});
I think the problem comes from the fact you are calling the popover() function before your document is properly loaded and then before $('#a1') in your example can match anything.
Check your updated jsfiddle here : http://jsfiddle.net/weuWk/325/
You need to call popover only when your document is ready like this :
$(document).ready(function() {
$('#a1').popover({title: "Hello"});
});
fixed http://jsfiddle.net/pieterwillaert/weuWk/327/
what you do is the following:
when the document is loaded you iterate through all your buttons (I did it by using 'span' you could easely change that too '.button')
you give each button a popover
$(document).ready(function() {
$('span').each(function(index) {
$(this).popover({title: "Hello"});
});
});​

bootstrap typeahead selector for dynamic page loading

When I load a page normally and use this code :
$('#clientName').typeahead({
//removed options since they are not needed for my question
});
The typeahead works fine on #clientName.
But when I load the input #clientName dynamically via AJAX then the above code doesn't work.
Is there some way to let it work?
It's equal to this problem :
$('#randomDiv').click(function() {
alert("Handler for .click() called.");
});
This one only works if the content is not dynamically loaded. But this code will work :
$(document).on('click','#randomDiv',function() {
alert("Handler for .click() called.");
});
So I would like to add the handler to the document or body, and not to the #clientName div itself.
I think you only have the choice to call $('#clientName').typeahead(...); again after inserting the input with the id clientName dynamically. If you capsules calling typehead into a function, you need only to call the function again without setting all options again.

Is there any callback function on click?

Let's say I have the following link:
<a href="#shippingaddress" onclick="return validateBillingAddress(document.addressInput,'ADDR_CONTINUE_ACTION',event);" >
EDIT
i am using multi page approach to show different section(divs) as a page
in that validate function I am validating the form and if everything is ok then displaying a hidden <div> and after the <div> is visible <spans> are getting applied by jquery mobile framework, untill and unless that div is hidden there is no span, but as that div become visible jquery mobile gets applied on it and appended some spans..i need to access this spans :
<span>blah</span>
So I want to change the text of this <span> after the click event, because the <span> is displayed after the click event.
So is there any way to do this?
In your validate function you can do this:
<div id="someDiv" style="display:none">
<span id="someSpan"></span>
</div>
<script type="text/javascript">
function validateBillingAddress() {
var valid = true;
... // do whatever you need to validate your input here and update valid variable
if (valid) {
$('#someDiv').show();
// if the validation is succesful invoke some function in the framework here
$.ajax({
...
success: function() {
//append the span to the div here
$(#someDiv').append('The span HTML content');
},
...
});
}
}
</script>
You could actually embed the validateBillingAddress into another function, containing the "callback" line as well
function doValidate( event ) {
validateBillingAddress(document.addressInput,'ADDR_CONTINUE_ACTION',event);
$('#spanElement').text( 'new text' );
}
And then
<a onclick="return doValidate( event );" >
Would be even better if you avoided using the onclick property in favor of a non-invasive event handling like
$('#aElement').click( function( e ) {
doValidate( e );
});
Do not use inline javascript...
$("#validate").click(function(){
// validate billing address
});
<a id="validate">Validate</a>
To create a span and attach a listener to it, then append to the div:
$("<span />").click(function(){
$(this).text("New Text");
}).appendTo("#divToShow");
Edit:
Since you haven't provided much information, the only thing I can help you out is:
1- To access all spans within the div, you do:
$("#myDivId span")
2- To access only spans that are direct children of the div, you do:
$("#myDivId > span")
3- To access only the last span within the div, you do:
$("#myDivId span:last")
More than that, only if you provide some actual generated code

Categories

Resources