jquery add toggle function to div after adding html to it - php

How can I add toggle function to a div which is populated with ajax response on click. Right now i can achieve the both functions but I need two clicks to get the div displayed after getting populated. Can I get this done at one click (i.e populating the div and adding toggle function)?
Any help would be greatly appreciated.
My code:
$(document).ready(function(){
$(".ex2").on('click', '.spnSelected', function() {
var self = $(this).closest("tr");
var col1_value = self.find(".col1").text();
$.ajax({
type: 'GET',
url: 'reportForm.php',
data: { propid: col1_value },
success: function(response) {
$('#form'+col1_value).html(response);
$('#form'+col1_value).toggle();
}
});
});
});

Second line $(".ex2").on('click', '.spnSelected', function() { change to $("body").on('click', '.ex2 .spnSelected', function() { should work like charm.
in you code you attached event on .ex2 click, so if you adding more .ex2 elements with ajax. you don't have event attached on new elements. when you attact click event on body and then check if .spnSelected clicked this shuld work with new elements.

Related

.on('click') doesn't work, but all other handlers do

I recently asked a question about triggering dynamically created divs, and was introduced to the .on() function.
'keyup' works great, 'mouseover' works, a few others I've tested work but 'click' just will not fire.
I created added information to a div via ajax and .php which holds some data like this:
function loadNewcomment(divID) {
$.ajax({
url: templateUrl+"/enternote.php",
cache: false,
success: function(html){
$("#"+divID).append(html);
}
});
}
I wanted to trigger on keyup for an element within that created div and this code works for that:
$("#notebox").on('keyup', '.note-field', function(event){
var thisString = $(this).val();
$keyLength = thisString.length;
$rowCount = Math.ceil($keyLength/40);
$currentRow = $(this).attr("rows");
if($currentRow < $rowCount){
$(this).animate({rows:$rowCount},50);
}
});
This code however does NOT work:
$("#notebox").on('click', '.note-field', function() {
alert("clicked");
});
dynamic DOM and jQuery is a pain. I know its deprecated but I have used in the past with great results: http://api.jquery.com/live/
FWIW - you could also try using bind() - http://api.jquery.com/bind/
I had an .stopPropagation(); somewhere else in the code in the encompassing div, I commented it out for now and it works, thanks.
Is it possible to attach click event after html is appended.
function loadNewcomment(divID) {
$.ajax({
url: templateUrl+"/enternote.php",
cache: false,
success: function(html){
$("#"+divID).append(html).bind('click', function() { /* Click event code here */ }); // id divID is #notebox
}
});
}
You can just use click like this:
$("#notebox").click( function() {
alert("clicked");
});
http://jsfiddle.net/7MBw4/

Other jquery functions NOT working after successful ajax function

EDIT
JQUERY-AJAX REQUEST CODE:
<script type="text/javascript">
$(document).ready(function(){
$(".form").submit( function(e) {
e.preventDefault();
var form = $(this);
var div_add_comment = $(form).parent();
var div_comments = $(div_add_comment).parent();
$.ajax({
type: "POST",
data: $(form).serialize(),
url: "includes/comment.php",
success: function(msg){
$(div_comments).html(msg);
}
});
return false;
});
});
</script>
JQUERY SHOW ALL - COLLAPSE COMMENTS CODE
<script type="text/javascript">
$(document).ready(function(){
$('.see_all').click(function(){
var thisItem = $(this);
thisItem.parent().find('#comment2').slideDown('fast');
thisItem.parent().find('.collapse').css('display','inline-block');
thisItem.css('display','none');
return false;
});
$('.collapse').click(function(){
var thisItem = $(this);
thisItem.parent().find('#comment2').slideUp('fast');
thisItem.css('display','none');
thisItem.parent().find('.see_all').css('display','inline-block');
return false;
})
})
</script>
JQUERY REMOVE DEFAULT VALUE TEXT UPON FOCUS - TEXTAREA
<script type="text/javascript">
$(document).ready(function(){
var Input = $('textarea[name=comment]');
var default_value = Input.val();
$(Input).focus(function() {
if($(this).val() == default_value)
{
$(this).val("");
}
}).blur(function(){
if($(this).val().length == 0)
{
$(this).val(default_value);
}
});
})
</script>
Please let me know if you need anything else, I have the damndest of time copying code and formatting it in these posts.
END EDIT
I am having a weird little problem. I have created a jquery-ajax function to transfer data from a comments section of my page. The page has an instance of this form under each user post. So this page will have X amount of posts with X amount of comments for each posts, like a social network. My ajax request sends, recieves and displays the data perfectly BUT I have two other jquery functions called on elements inside that no longer work after the ajax function returns the html. All the other ones not acted upon by the ajax function STILL WORK. I have the checked and rechecked the response html from the ajax function and it is identical to the html of a standard post-comment instance.
Please let me know what you would like to see or if you have questions.
Thanks, your help is always appreciated!
Be sure to bind the jQuery functions in such a way that the element doesn't have to exist.
$('ul').on('click', 'li', function(){ /* do something */ });
This will execute on LIs that have been added after the binding of the function.
In your case you would want to bind to the parent of the comments section and target the elements that have the click behavior.
$('.comments')
.on('click', '.see_all', function(){...})
.on('click', '.collapse', function(){...})
.on('focus', 'textarea[name=comment]', function(){...})
.on('blur', 'textarea[name=comment]', function(){...})
Try removing the $() from form.
You have this:
var form = $(this);
var div_add_comment = $(form).parent();
var div_comments = $(div_add_comment).parent();
It should be this:
var form = $(this),
div_add_comment = form.parent(),
div_comments = $(div_add_comment).parent();
Since you declared var form = $(this); you don't need to wrap form...how you have it now is the equivalent of $((form))
Not sure if this will fix your problem, but jQuery may be getting hung up on this since you are spawning children from $(this).

Jquery autosuggestion close when click everywhere

I have an Jquery Autosuggest dropdown.
The function is running ok.
Now I want when I right click or click everywhere the display box must be keep show. Because I found problem when autosuggest search have a link. The link can't open because before click link the dropdown box closed.
Here it my JS code so far :
$(document).ready(function(){
$(".searchs").keyup(function()
{
var searchbox = $(this).val();
var dataString = 'searchword='+ searchbox;
if(searchbox=='')
{
$("#display").hide();
}
else
{
$.ajax({
type: "POST",
url: "searchs.php",
data: dataString,
cache: false,
success: function(html)
{
$("#display").html(html).show();
}
});
}
return false;
});
$(".searchs").blur(function(){
$("#display").hide();
});
$(".searchs").focus(function(){
var seachbox = $(searchbox).val();
if(seachbox != '')
{
$("#display").show();
}
});
});
Someone have an idea ?
this the way to keep showing AutoComplete result list: DEMO
$("#tags").autocomplete({
source: availableTags,
close : function (event, ui) {
val = $("#tags").val();
$("#tags").autocomplete("search", val).focus();
return false;
}
});
The reason your drop down box is closing is because whenever you deselect you 'searchs' class, you hide the drop down box. To fix this, you can try a couple different things.
1: put your drop down box(the one with an id of 'display') in the the
'searchs' class. that would look something along the lines of:
<div id = "display" class = "searchs"></div>
2: when your $(".searchs").blur event is triggered, before executing $("#display").hide(); check if the new focus is your display div:
$(".searchs").blur(function(){
if($("#display").blur(function(){ //<--- if the new focus is not the display div, then hide display
$("#display").hide();
}
});

Get only part of the message and reload only one div

this is an ajax method that inserts the data into a db and should supposedly display the new content.
<script type = "text/javascript">
$(document).ready(function() {
$('#submit').live('click', function(eve) {
eve.preventDefault() ;
var form_data = {
title: $('#title').val()
};
$.ajax({
url: "http://localhost/ci/index.php/chat/comment",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
});
});
</script>
However in my /chat/comment, i am loading the view again, i.e, user submits a comment, load the view again and the comment should be there. My response from server is the view's HTML. However the view comes with all the divs and there are many of them. I need to retrieve only part of the div, say, #commentspace from the ajax on success.
Look at the jQuery $.load() function?
Example
Inside "firstpage.html"
$('#content').load('secondpage.html #content');

Jquery function not loading after refreshing div using Ajax

I have a several divs that a refreshed using Ajax after the user clicks on a link on the page.
Here's my code for the Ajax refresh div:
<script type="text/javascript"><!-- AJAX CALL FOR MY PICTURES -->
$(document).ready(function() {
$('#pictures_wrapper a.delete_image').live('click', function(e){
$('#pictures_wrapper').load( $(this).attr('href') + ' #pictures_wrapper' );
e.preventDefault();
});
});
</script>
On this same page, I am loading this Jquery effect:
<script type="text/javascript"><!-- HOVER OVER ITEMS CHANGE BG COLOR -->
$(document).ready(function() {
$(".item_control_box").hide();
jQuery('.each_item_container').hover(function() {
jQuery(this).find('.item_control_box').show()
}, function() {
jQuery(this).find('.item_control_box').hide();
});
});
</script>
My issue is that when the user click on the link to refresh the Divs, this jquery effect breaks and no longer works. I'm thinking that I have to "reload" this function some how since only the div is being reloaded and not the whole page. How can I keep this Jquery function working after refreshing a div?
You should use the callback function of the load, means u recall the jquery after loading has completed.
$('#pictures_wrapper').load( $(this).attr('href') + ' #pictures_wrapper', , function () { //hover effect function } );
Hope this help :)
Your code should work if you change your .bind() calls to .live():
jQuery('.each_item_container').live('mouseenter', function() {
jQuery(this).find('.item_control_box').show()
}).live('mouseleave', function() {
jQuery(this).find('.item_control_box').hide();
});
.hover() is the same thing as using .bind('mouseover', function () {...}) and .bind('mouseout', function () {...})
When you want to bind event handlers to elements not yet in the DOM you can use .live() or .delegate(): http://api.jquery.com/live/, http://api.jquery.com/delegate/
Attach an event handler for all elements which match the current
selector, now and in the future.
As of jQuery 1.7 you should be using .on() as .bind(), .live(), and .delegate() are depreciated: http://api.jquery.com/on/
Better put the code in a custom function with a name
function effectLoad(){
$(".item_control_box").hide();
jQuery('.each_item_container').hover(function() {
jQuery(this).find('.item_control_box').show()
}, function() {
jQuery(this).find('.item_control_box').hide();
});
}
then put the function in your ajax success function
$.ajax({
url: 'your_php_file.php',
type: 'POST',
data:formData,
success: function(response)
{
$("#formbox").html(response);
effectLoad();
}
});
Hope it will work.
Thanks
as #Guillaume Cisco mentioned in the comments you have to rebind the hover effect to dynamically inserted elements in the DOM, you can do it like
$(".item_control_box").live(
{
mouseenter:function(){
jQuery(this).find('.item_control_box').show();
},
mouseleave:function(){
jQuery(this).find('.item_control_box').hide();
}
});

Categories