Adding html elements from variable using jquery? - javascript

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.

Related

jQuery append function is just appending the html but not the classes related to it

I am using php laravel and so it uses blade template to render the views. Following is the javascript code to append html script :-
$(function () {
var count = 0;
$("#min_bonus_value").click(function () {
count++;
var min_bonus_html =
'<div class="min_bonus_row">' +
'<hr>' +
'<div class="row">' +
'<div class="col-md-2">' +
'<div class="form-group">' +
'<label for="bonus_day[' + count + ']">#lang('admin.message759')<span class="text-danger">*</span></label>' +
'<select class="select2 form-control" id="bonus_day[' + count + ']" name="bonus_day[' + count + '][]" data-placeholder="#lang('admin.message759')" multiple>' +
'<option value="1">Monday</option>' +
'<option value="2">Tuesday</option>' +
'<option value="3">Wednesday</option>' +
'<option value="4">Thursday</option>' +
'<option value="5">Friday</option>' +
'<option value="6">Saturday</option>' +
'<option value="7">Sunday</option>' +
'</select>' +
'</div>' +
'</div>' +
'</div>' +
'</div>';
Following is the piece of blade template code where the above html needs to be appended, I want to append 'select2' class which is styled to select multiple days, but in vain :-
<div id="minimum_bonus">
</div>
I may be off here but when you say "not the classes", do you actually mean the Javascript/jQuery funcionality?
If so, I'll try to explain what is happening: when you initialize a jQuery plugin, like select2, it acts upon what exists in the DOM at the moment you initialize it. So if you later create new items, these won't have the select2 functionality, unless you initialize it again for said new items.
I suggest you create a function to initialize select2 and call it whenever you add new elements to your DOM. You'd need to somehow single out the elements that have already been initialized. You can do so with a class, in this example, the class is 'select2-enabled'. Like this:
function initSelect2() {
$(".select2").each(function(){
if (!$(this).hasClass('select2-enabled')) {
$(this).addClass('select2-enabled');
$(this).select2({
// all your select2 options
});
}
});
}
And then, after you append your new html, you can call your function to initialize select2 on the new elements:
$(parentElement).append(newHTML);
initSelect2();

Jquery attribute not being added to div element

I have a div as follows
'<div class="ctrl-info-panel col-md-12 col-centered">'+
'<h2>You do not have any projects created at the moment.</h2>'+
'<div id="t1" style="display:inline-flex" data-toggle="tooltip">'+
'<p><span>Create Project</span></p>'+
'</div>'+
'</div>'
I am trying to add an attribute to #t1 in the following function.
function appendCreateprojectDisabled(noOfDatasets) {
var classAppend = '';
if(noOfDatasets == 0) {
$("#t1").attr('title','No datasets available');
classAppend = 'cu-level-btn-disabled';
}
return classAppend;
}
But the attribute is not being added. I am not getting a text in the tooltip. what's the issue here?
Note that noOfDatasets is 0.
To answer your question, the issue in your code is the order is is executed.
When the function appendCreateprojectDisabled(noOfDatasets) is executed, it looks for the element $("#t1"), which does not exists yet since the following string has not been added to the HTML document yet:
'<div class="ctrl-info-panel col-md-12 col-centered">'+
'<h2>You do not have any projects created at the moment.</h2>'+
'<div id="t1" style="display:inline-flex" data-toggle="tooltip">'+
'<p><span>Create Project</span></p>'+
'</div>'+
'</div>'
As you may notice, the above code has the element id="t1", which doesn't exists at the time the function appendCreateprojectDisabled(noOfDatasets) is called.
You created the div here dynamicly in javascript, so you just have a string here.
There is two way for you.
First you should write in on the page.
var htmlString = '<div class="ctrl-info-panel col-md-12 col-centered">'+
'<h2>You do not have any projects created at the moment.</h2>'+
'<div id="t1" style="display:inline-flex" data-toggle="tooltip">'+
'<p><span>Create Project</span></p>'+
'</div>'+
'</div>';
function appendCreateprojectDisabled(noOfDatasets) {
var classAppend = '';
$("#aDivInYourPage").html(htmlString);//after register your div you can find your 't1' div. if not it will be undefuned for you.
if(noOfDatasets == 0) {
$("#t1").attr('title','No datasets available');
classAppend = 'cu-level-btn-disabled';
}
return classAppend;
}
The other way is you can put a spetial character to your div like {TitleAttribute} and replace this with your attribute like title='No datasets available'
you can achieve this by parsed the string to HTML element.
Try this code.
$(document).ready(function () {
function appendCreateprojectDisabled(noOfDatasets, divElement) {
var classAppend = '';
if (noOfDatasets == 0) {
divElement.find("#t1").attr('title', 'No datasets available');
classAppend = 'cu-level-btn-disabled';
}
return classAppend;
}
var divElement = '<div class="ctrl-info-panel col-md-12 col-centered">' +
'<h2>You do not have any projects created at the moment.</h2>' +
'<div id="t1" style="display:inline-flex" data-toggle="tooltip">' +
'</div>' +
'</div>'
divElement = $(divElement);
var paraElement = '<p><span>Create Project</span></p>'
divElement.find("#t1").append($(paraElement));
$(document.body).append(divElement);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Hope this will help you.
Do something like this:
var classAppend = "";
var classAppend = appendCreateprojectDisabled(noOfDatasets);
After making sure classAppend have some value; you can append your html wherever you want.
var html = '<div class="ctrl-info-panel col-md-12 col-centered">' +
'<h2>You do not have any projects created at the moment.</h2>' +
'<div id="t1" style="display:inline-flex" data-toggle="tooltip">' +
'<p><span>Create Project</span></p>' +
'</div>' +
'</div>';
Use this piece of html wherever you want now. The below function is called first.
function appendCreateprojectDisabled(noOfDatasets) {
var classAppend = '';
if(noOfDatasets == 0) {
$("#t1").attr('title','No datasets available');
classAppend = 'cu-level-btn-disabled';
}
return classAppend;
}

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

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

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.

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