Jquery click action doesn't work to ajax appended dynamic content - javascript

Like in the screenshot I have div element working as button to expand area inside comments-loaded-more-wrap div element. Inside this div there are paragraphs if that div contains any text content. If there are no paragraphs comments-load-more div don't appear at first. It appears after I add text from input element. So I'm appending texts inside comments-loaded-more-wrap. but after append my expand jquery doesn't work. When I refresh the page its working fine.
I want to know how to reload the element to inherit jquery or is there any way to solve it?
If there is not content highlighted button don't appear at first. It comes when I add something from comment field. But when I click button the jquery doesn't work. If there are more that button is there at first time and it's working if I add something from comment field.
Here is the graphical view of my button:
here is my data append ajax:
//get comment input box id by its name
var elements = document.getElementsByName( 'comment_input' );
//on enter key press
$(elements).each(function(){
var cmt_id = $(this).attr('id');
var resp = cmt_id.split("_");
$('#comment_post_'+resp[2]).on('click', function(event) {
var comment = $('#'+cmt_id).text();
var form_data = {
comment_input : comment,
post_Id : resp[2],
ajax : '1'
};
$.ajax({
url: "comment/post_comment/",
type: 'POST',
async : true,
dataType:"json",
data: form_data,
success: function(data) {
$('#'+cmt_id).text('');
var latest_comment = data;
print_latest_comment(latest_comment);
}
});
});
});
function print_latest_comment(data){
$ght = $('#post_comment_id_'+ data.post_Id + ' .mCSB_container').children().length;
if($ght==0){
$('#post_comment_id_'+ data.post_Id + ' #panel1').append('<div class="comments-load-more" id="more-load-'+ data.post_Id +'">'+
'<span class="load-more-comments-count"><span class="new_cmt_count_'+ data.post_Id +'"></span></span>'+
'</div>');
$( '#post_comment_id_'+ data.post_Id + ' .mCSB_container' ).append('<div class="post-meta-single-comment" name="comment-field" id="comment_'+ data.comment_id +'">'+
'<div class="post-exp-top-meta-left">'+
'<div class="post-exp-top-meta-left-profile-picture">'+
'<a href="user?id='+ data.user_Id +'" ><img src="uploads/'+ data.pro_image.name + data.pro_image.ext +'"/></a>'+
'</div>'+
'<div class="post-exp-top-meta-left-profile-info">'+
'<div class="post-exp-top-meta-left-profile-name">'+
'<a href="user?id='+ data.user_Id +'" >'+ data.user_details.full_name +'</a>'+
'</div>'+
'<div class="post-exp-top-meta-left-profile-modes">'+
'<ul>'+
'<li><div class="time"><abbr class="timeago" title="'+ data.comment_datetime +'">less than a minute ago</abbr></div></li>'+
'<li class="flag"></li>'+
'</ul>'+
'</div>'+
'</div>'+
'</div>'+
'<div class="post-meta-single-comment-vote">'+
'<a class="comment-edit_'+ data.comment_id +'" title="Edit Comment" id="comment-edit">Edit</a>'+
'<i class="fa fa-times fa-2 close-comment" style="display: none;" title="Remove Comment" id="delete_comment_'+ data.comment_id +'"></i>'+
'<div class="comment-count">6</div>'+
'<div class="comment-icon"></div>'+
'</div>'+
'<div class="clearfix"></div>'+
'<div class="comment-content comment_content_'+ data.comment_id +'">'+
'<span class="comment-content-alone_'+ data.comment_id +'">'+ data.content +'</span>'+
'<input type="text" id="edit_comment_'+ data.comment_id +'" name="cmt_edit_input" style="display:none; padding:5px; height: 30px;" value="'+ data.content +'" spellcheck="true" />'+
'</div>'+
'</div>'
);
}
} // function end

I want to know how to reload the element to inherit jquery or is there any way to solve it?
If you add a button after pageload
$('#myNewButton').on('click', function....
Then it wont work, as the javascript has run, and it's not going to rerun to bind the click event to your post-ready button.
Instead, do this.
$('#myContainerThatExistsInSourceCode').on('click', '#myNewButton', function()....
This binds the clickevent to the parent, of your button, so the children wont have an event bound to it, but the child will trigger the event bound to the parent.

$('body').on('click', '#comment_post_'+resp[2], function(event) {
var comment = $('#'+cmt_id).text();
var form_data = {
comment_input : comment,
post_Id : resp[2],
ajax : '1'
};

Related

jquery call function from dynamic div

I am using jquery. I have a div that is populated by jquery. Inside div, there is a list of items under row tag. And, Inside, the dynamic div section, I also have a anchor tag. On clicking on that anchor tag, I want to call the ajax function. Is it even possible?
var content='';
$.each(products, function(key, value) {
content += '<div class="row">' +
'<img src="' + value.image + '" class="img img-responsive" style="height: 65px;"/>' +
'<h3>' + value.name + '</h3>' +
'<p>' + value.category + '</p>' +
'</div>' +
'Delete' +
'<hr>';
});
modal.find('.modal_product_list').html(content);
When the anchor tag is clicked, I want to call ajax function. Here is my ajax sample:
$('.delete_product_from_space').on('click', function(e) {
e.preventDefault();
alert('hello');
var product_id = $(this).attr('data-id');
});
The on click event is never fired. Is it possible to call like this? Or I am approaching in a wrong way?
You may try to add the event on modal, as the dynamically generated elements would not be available at the time of code execution. Try the below code,
$('.modal_product_list').on('click', '.delete_product_from_space', function(e) {
e.preventDefault();
alert('hello');
var product_id = $(this).attr('data-id');
});

How to write into div using javascript

I want to make a for example content variable in javascript which will have a html tags inside with certain values.
How can I put that in the div when button is pressed.
For example :
This is a content which I want to use:
var contentString = '<div id="info">'+
'<h2><b> Info:</b></h2>'+
'<div id="bodyContent">'+
'<div style=width:220px;display:inline-block;>'+
'<p> Name: '+ this.name + '</p>' +
'<p> Last name: '+ this.last+ '</p>' +
'<p>
'</div>'+
'</div>'+
'</div>'+
'</form>';
And I want to put it into : <div id=something"></div>
In javascript I can have something like:
$("#button").on('click', function() {
// What to put in here?
});
How can I put that in the div when button is pressed.
Like this:
$("#button").on('click', function() {
$('#something').html(contentString);
});
More info about html();
http://api.jquery.com/html/
It goes like this:
$("#button").on('click', function() {
$("#something").html(contentString);
});
If I'm not misunderstanding, then this will work:
$("#button").on('click', function() {
$('#something').html(contentString);
});
This does, of course, assume that you have an element with an id of button (though I assume you do, otherwise you wouldn't have put that jQuery).
JS Fiddle demo.
References:
html().
You should fix up your markup. You have unbalanced elements, and you can't have new lines in the string without escaping it. Try this instead:
var contentString = '<div id="info">'+
'<h2><b style="text-indent: 40px">Info:</b></h2>'+
'<div id="bodyContent">'+
'<div style="width:220px;display:inline-block;">'+
'<p style="text-indent: 1em">Name: '+ this.name + '</p>' +
'<p style="text-indent: 1em">Last name: '+ this.last+ '</p>' +
'</div>';
Note that I skipped the and replaced them with style attributes. You really should put these styles in a stylesheet, though.
$("#button").on('click', function() {
$('#something').html(contentString);
});
Keep in mind that the variables in contentString will not be evaluated when the click event on the button fires, meaning that this.name and this.last will not change. Do you need to update these values on click as well?

element.html() return empty on DOM ready

I am working on a countdown timer, using http://keith-wood.name/countdown.html.
My code looks like this,
$('.clock').countdown({until:new Date(2012, 11, 31), format: 'odHMS', onTick:watchCountdown, tickInterval:5, layout:
'<div id="timer">' +
'<div id="timer_labels">'+
'<div id="timer_months_label" class="timer_labels">Months</div>'+
'<div id="timer_weeks_label" class="timer_labels">Days</div>'+
'<div id="timer_days_label" class="timer_labels">Hours</div>'+
'<div id="timer_minutes_label" class="timer_labels">Minutes</div>'+
'</div>'+
'<div id="timer_months" class="timer_numbers"><span class="divide"></span><span>{onn}</span></div>'+
'<div id="timer_days" class="timer_numbers"><span class="divide"></span><span>{dnn}</span></div>'+
'<div id="timer_hours" class="timer_numbers"><span class="divide"></span><span>{hnn}</span></div>'+
'<div id="timer_minutes" class="timer_numbers"><span class="divide"></span><span>{mnn}</span></div>'+
'</div>'
});
As you onTick I call a function that looks like this,
function watchCountdown(periods) {
var $div = $("#monitor");
var html = $div.html();
var checking = setInterval(function() {
var newhtml = $div.html();
if (html !== newhtml) {
myCallback($div);
}
},100);
$('#monitor').html('<div id="timer_minutes" class="timer_numbers"><span class="divide"></span><span class="minutes">' + periods[5] + '</span></div>');
}
In the function above there is a check for html != newhtml however html is returning as an empty variable evening though there is HTML in the #monitor element. How can I make it realise there is content to check against?
You don't understand what is DOM ready, it fires only once, when the DOM is fully loaded and rendered from the server.
If you change the DOM with javascript, it has no effect on the DOM ready event.
$('#monitor').html('<div id="timer_minutes" class="timer_numbers"><span class="divide"></span><span class="minutes">' + periods[5] + '</span></div>');
The code above will not cause delay or trigger again the DOM ready event.

Adding html elements from variable using jquery?

I am trying to add elements to specific div, but not using clone(), because i need fresh copy of original elements on every add, mainly because elements are draggable and their values are being change by user? So i have my html in variable, i need to take this elements and add them on click to another elem. ?
$(document).ready(function (e) {
var $gElem = $(
'<div class="distributionWrapper" id="element_0">' +
'<div class="cbox cboxQuarterWidth">' +
'<select id="combobox100">'+
'<option>1</option>'+
'<option>2</option>'+
'</select>'+
'</div>'+
'<div class="help"></div>'+
'<div class="cbox cboxEighthWidth"><span>'+
'<select id="combobox200" name="PeriodId">'+
'<option>1</option>'+
'<option>2</option>'+
'</select>'+
'</span></div>'+
'<div class="clear" id="clearDistribution"></div>'+
'<div class="add" id="addDistribution"></div>'+
'</div>'
);
$('.mainSearch').html($gElem); // initial load of element
$("#combobox100").combobox();
$("#combobox200").combobox();
var counter = 1;
$('.add').live('click', function () {
if ($('.distributionWrapper').length === 6) return;
//var el = $('.distributionWrapper:first').clone().attr('id', 'element_' + ++counter).appendTo('.mainSearch');
$('.mainSearch').add($gElem).attr('id', 'element_' + ++counter);
// here on click add gElem to .mainSearch and set atribute to .distributionWrapper
});
$('.clear').live('click', function () {
if ($('.distributionWrapper').length === 1) return;
$(this).parents('.distributionWrapper').remove();
});
});
Any ideas?
try this
$('.mainSearch').append($gElem);
$('.mainSearch').children('.distributionWrapper:last').attr('id', 'element_' + ++counter);
Store the html as a string in a javascript variable and create a jQuery element every time you need one from that string.
var elemHtml =
'<div class="distributionWrapper" id="element_0">' +
'<div class="cbox cboxQuarterWidth">' +
'<select id="combobox100">'+
'<option>1</option>'+
'<option>2</option>'+
'</select>'+
'</div>'+
'<div class="help"></div>'+
'<div class="cbox cboxEighthWidth"><span>'+
'<select id="combobox200" name="PeriodId">'+
'<option>1</option>'+
'<option>2</option>'+
'</select>'+
'</span></div>'+
'<div class="clear" id="clearDistribution"></div>'+
'<div class="add" id="addDistribution"></div>'+
'</div>'
$(function(){
//your initial element
var $elem1 = $(elemHtml);
}
function someHandler(){
//you can create fresh new elements anywhere without cloning
var $elem2 = $(elemHtml);
}
The duplicate IDs need to be removed. But that's outside the scope of your question.

How to fetch the id of dynamically generated textboxes?

How is it possible to get the id of the dynamically generated textboxes using jquery?. I need to fire the TextChanged event for the corresponging textbox. There is no method reference for the textboxes in the code behind.How can i refer to any method in the codebehind on firing the event. Somebody please help. I dont know jquery much. The entire script im using is as as follows:
<script type="text/javascript">
$(init);
function init()
{
$('#test').droppable(// Div Control
{
drop: handleDropEvent
});
$('a').each(function(idx, item) {
$(item).draggable({ cursor: 'move', helper: 'clone' })
});
}
$(function() {
$("#draggable").draggable(); //Nothing to do with this div
});
function handleDropEvent(event, ui)
{
var draggable = ui.draggable;
document.getElementById('test').innerHTML += addColumn(draggable.attr('text')) + '<br>';
}
function addColumn(column)
{
var iHtml;
// This code will generate a checkbox and a textbox. I need to fire the event of thus generated textboxes.
iHtml = '<div id="dv' + column + '" width="100px;" height="20px;" padding: "0.5em;"> ' + '<span title="ToolTipText">' + '<input type="checkbox" id="cb' + column + '" value="' + column + '" /> <label for="cb' + column + '">' + column + '</label></span><input type="text" runat="server" id="aln' + column + '"> </div>';
return iHtml;
}
</script>
There's two ways: keep the generated element, or generate an ID when you generate your new element.
a) keep the generated element
This requires that you don't use innerHTML, but create the element (with document.createElement, or with jQuery's $), and then you can use the element directly (no need to call it by ID any more). For instance, with jQuery:
var container = $('#container');
var myDiv = $('<div id="myDiv"/>');
var myCheck = $('<input type="checkbox"/>');
myDiv.append(myCheck);
container.append(myDiv);
b) generate the ID
container.innerHTML = '<div id="myDiv"><input type="checkbox" id="myCheck"/></div>';
// and after this you can get them by ID:
var myCheck = $('#myCheck');
I would just add a class to the textbox in your iHtml then use .live() event
replace your iHtml with this
iHtml = '<div id="dv' + column + '" width="100px;" height="20px;" padding: "0.5em;"> ' + '<span title="ToolTipText">' + '<input type="checkbox" id="cb' + column + '" value="' + column + '" /> <label for="cb' + column + '">' + column + '</label></span><input class="myclass" type="text" runat="server" id="aln' + column + '"> </div>';
then add the live event
$('.myclass').live('change', function() {
alert(' Live handler called.');
});
here is a WORKING DEMO

Categories