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?
Related
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');
});
I'm using javascript to add html to my 's.
I made a loop that goes around all projects there are. There are multiple projects and in every project there are multiple pictures.
The first part creates the first projecttitle within a div that gets an id(the projectname) and the first pictures.
$( ".projectbeeldcontainer" ).append(
'</div>'+
'<h1 class="projecttitel" id="'+name+'">'+name+'</h1>'+
'<div class="row dashboardrow" id="'+name+'id">'+
'<div class="col-sm-2">'+
'<div class="thumbnail">'+
'<a href="/w3images/lights.jpg">'+
'<img src="projectbeelden/'+name+'/'+decodeURI(image)+'" class="img-rounded">'+
'</a>'+
'<div class="caption tags">'+
'<p>titel van project</p>'+
'</div>'+
'</div>'+
'</div>';
);
After this, the script will check if the projectname of the next image allready exists. If it does exist (because we added it with the code above), then it will insert a new div inside of the project div we created:
document.getElementById(name+'id').append(
'<div class="col-sm-2">'+
'<div class="thumbnail">'+
'<a href="/w3images/lights.jpg">'+
'<img src="projectbeelden/'+name+'/'+decodeURI(image)+'" class="img-rounded">'+
'</a>'+
'<div class="caption tags">'+
'<p>titel van project</p>'+
'</div>'+
'</div>'+
'</div>'
);
The problem i have now is that the first line of code successfull creates the div's and the image. The second code works for 98%.
It does recognise the div with the id and puts the content in it. But the problem is that it adds quotes before my first line and after. So it looks like it thinks it's a string and not html.
So it literally adds "<div ..." on my page.
Can anyone help me please? Sorry for the bad spelling and grammar.
Use innerHTML instead of append.
document.getElementById(name+'id').innerHTML += "<div> put your html </div>";
Append adds a textNode. Better way is something like this by generating it and inserting into the DOM:
var el = document.createElement("div");
el.appendChild(document.createTextNode("Put yout HTML"));
document.getElementById(name+'id').appendChild(el);
The problem is that you are literally telling it to append a string to the DOM, you are not creating an element that you can insert.
If you wrap the html that you are trying to append in the jQuery wrapper $('<div class="col-sm-2">....</div>');, then it will be treated by jQuery as an a jQuery object and should then be able to be inserted in the manor that you need.
This work to me
var stringToHTML = function (str) {
var parser = new DOMParser();
var doc = parser.parseFromString(str, 'text/html');
return doc.body;
};
$( ".projectbeeldcontainer" ).append(stringToHTML('<p>text</p>'))
DEMO
var insertData = '<div class="col-sm-2">'+
'<div class="thumbnail">'+
'<a href="/w3images/lights.jpg">'+
'<img src="" class="img-rounded">'+
'</a>'+
'<div class="caption tags">'+
'<p>titel van project</p>'+
'</div>'+
'</div>'+
'</div>';
document.getElementById('a').innerHTML = insertData;
<div id="a"></div>
You can just use < and > instead of "<" and ">" in your code. Browser will not recognize this string as html code and print it as a plain text.
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'
};
I have a looong string of HTML inside a Javascript.
Is there any way I can auto indent it?
The conventional way in Sublime Text (pressing F12) won't work because Sublime doesn't know it's HTML.
Here's a portion of it:
'<ul class="obj-ul">' +
'<li ng-repeat="(key, val) in argVal">' +
'<p class="arg-key">{{key}}</p>' +
'<span class="arg-colon">:</span>' +
'<div ng-if="utils.isPrimitive(val)" class="inline-block">'+
'<p ng-click="editVal=!editVal" ng-show="!editVal" class="arg-val">{{argVal[key]}}</p>' +
'<input ng-show="editVal" ng-model="argVal[key]" ng-blur="editVal=!editVal" class="arg-val" />' +
'</div>'+
'<div ng-if="!utils.isPrimitive(val)" class="inline-block">'+
'<rapid-args arg-val="argVal[key]"></rapid-args>' +
'</div>'+
'</li>' +
'<div ng-if="utils.showButtons.showButtonInObject(templateArgVal)">' +
'<button ng-click="vars.show_addObjectItem=!vars.show_addObjectItem">+</button>'+
'<div ng-if="vars.show_addObjectItem" class="add-item">'+
'<input ng-model="newKey" type="text" class="arg-key"/>'+
'<span class="arg-colon">:</span>' +
'<div id="new-value">'+
'<div ng-if="!vars.show_addObjectValue" class="value-types">'+
'<p ng-click="objects.addItem(argVal, newKey, \'array\'); vars.show_addObjectItem=!vars.show_addObjectItem" class="value-types-type">Array</p>'+
'<p ng-click="objects.addItem(argVal, newKey, \'object\'); vars.show_addObjectItem=!vars.show_addObjectItem" class="value-types-type">Object</p>'+
'<p ng-click="vars.show_addObjectValue=!vars.show_addObjectValue" class="value-types-type">String</p>'+
'<p>{{showValInput}}</p>' +
'</div>' +
'<div ng-if="vars.show_addObjectValue">'+
'<input ng-model="newVal" type="text" class="arg-key"/>'+
'<button ng-click="objects.addNewKeyVal(argVal, newKey, newVal); vars.show_addObjectValue=!vars.show_addObjectValue">✓</button>'+
'<button ng-click="vars.show_addObjectValue=!vars.show_addObjectValue">Cancel</button>'+
'</div>' +
'</div>' +
'</div>' +
'</div>'+
'</ul>' +
Sort of what Mouser suggested in a comment, you're going to have to remove the apostrophe's and plus signs from this code using a find+replace tool (notepad++ has one, I'm sure sublime will have one too) then do your formatting thing with F12 in sublime and then re-add your apostrophe's and plus signs using regex.
Here's a demonstration of how to remove your string formatting using Notepad++ (or any Regex based find and replace string manipulator):
Find What: '(.*?)'[\s]?\+
Replace With: $1
To add them back again after you've formatted you can simply do:
Find What: (.*)
Replace With: '$1' +
Here's a way:
Remove all the quotes and + used to concatenate the different lines, i.e., make it a single string (you may use search-replace -> replace all) without any + in between to join.
Copy the resulting string and paste at http://www.freeformatter.com/html-formatter.html or any other online html formatter.
Copy the result and paste it back.
Hope it helps.
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.