How to handle input parameters while generating dynamic html from jquery function - javascript

I am using below function to generate dynamic HTML.
function (content) {
$('#divMessage').append('<span>'+ content+ '</span>');
}
Here I am appending content in div with id divMessage.
Here input parameter content can be any text passed to this function.
I am facing problem when I pass data containing html elements as it distorts html. I am not aable to paste it here as its get dostorted here in stack overflow editor as well.
How can I resolve this issue, TIA.
It should append what is being passed, don't want to convert html tags to html, if html tag with data is passed then html tag with data should be the ouput.

To resolve this you need to only paser the content text to HTML
Just do this
content= $.parseHTML(content);
$('#divMessage').append('<span>'+ content+ '</span>');
Hope it will help!

You can pass html value like this.
function AddContent(content) {
$('#divMessage').append('<span>'+ content+ '</span>');
}
$("#divAppendMessage").on("click", function() {
//$('#divMessage').html(''); // If you want to clear div before append
var html='';
html+='<h1>My new message</h1>';// You can add mark up like this.Be sure for closing tag.
AddContent('<h1>My new message</h1>');// Pass html without generate markup as OP say on comment.
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='divMessage'>
</div>
<button id='divAppendMessage'>Add Message</button>
May be
this fiddle solve your problem. Before get input from user convert it and reset it when bind.

Related

jQuery: Best way to append to html of a paragraph inside a textarea

I have a textarea that contains variable html content which is always wrapped in a paragraph (p) tag.
HTML (before appending):
<textarea rows='7' class='form-control' id='comments'><p>My variable HTML content.</p></textarea>
I fetch this content using the following in jQuery:
jQuery:
$('#comments').val();
Now I need to append HTML at the end of this paragraph but inside the p tag.
HTML (after appending):
<textarea rows='7' class='form-control' id='comments'><p>My variable HTML content. Some appended HTML.</p></textarea>
I can of course replace the last 4 characters of the above (which is the closing p tag), then append my HTML and then add the closing p tag again.
Can someone tell me if there is a better way to achieve the same in jQuery ?
Many thanks in advance for this, Tim.
Parse the string value of the textarea as HTML, and insert whatever you like, then pass the string value of the HTML back
$('#comments').val(function(_, val) {
return $('<div />', {html:val}).find('p').append('content').end().html();
});
FIDDLE
This could do the trick
var html = $('#comments').val();
$('#comments').val(
$(html).append(' Some appended HTML.')[0].outerHTML
);
DEMO
You could insert the value into a temporary div, add an element to the <p>-element inside the temporary div and fetch the renewed content again:
var tmpDiv = $('<div></div>'); //create temporary element
tmpDiv.html($('#comments').val()); // add HTML from textarea
$(someHtml).appendTo($('p', tmpDiv)); // append custom HTML to P inside temp element
newTextAreaValue = tmpDiv.html(); // retrieve new value
Ok. I REALLY love this!
$('#comments').text($($('#comments').text()).append(' a new insert!').text());
Don't look at it too long. Could hurt your eyes :-)

process html string before insertion

I want to load some html from server, I store the loaded html in a string then I want to modify the values of certain tags and elements within that string before appending it :
here is how I'm trying to do it :
script of test1.html :
<head>....</head>
<body> <div id="main"></div></body>
<script>
$(document).ready(function(){
$.get("test2.html").done(function(data){
$("#rf", data).val("new value");
$("#main").append(data);
});
});
</script>
test2.html
<p id="rf"> <b>old value</b></p>
The first problem is trying to target the val() method of a paragraph. That will not do anything as it has no val property to return. You need to use text or html to replace the content.
Second, convert the HTML string to a DOM tree first with $(data) (see notes below as to why I use a dummy div and html() instead), then find the element, change it etc then append the new tree to the target:
JSFiddle: http://jsfiddle.net/TrueBlueAussie/NWj62/1/
var html = '<p id="rf"> <b>old value</b></p>'
$(document).ready(function () {
var $html = $("<div>").html(html);
$html.find("#rf").html("new value");
$("#main").append($html);
//$.get("test2.html").done(function(data){
// $("#rf", data).val("new value");
// $("#main").append(data);
//});
});
You need to wrap the incoming HTML in a dummy div as find will not match the top element of the tree.
I substituted dummy data so you could see it working without the ajax call.
Note: $(htmlstring) will collapse html and body tags into a flatter structure than you might expect, but your example only has the paragraph so is fine.
Your code will be something like:
$(document).ready(function () {
$.get("test2.html").done(function(data){
var $html = $("<div>").html(data);
$html.find("#rf").html("new value");
$("#main").append($html);
});
});
You want some sort of template functionality, since getting HTML from server and transforming it into a DOM tree and then applying manipulations manually is a lot of code repetition for nothing. Also, it's relatively expensive to do dynamic tree manipalations.
Either the html is processed on the server or on the client side, is your choice.
Backend templates: depends on your backend framework (ie. Django has its own template module).
Fronted templates: You can use Underscore templates or Handlebars templates (more similar to Django templates).

Change text of child

I'm trying to make a add to favorite system. I have a function which alerts the proper id I want to add.
I use:
<script type="text/javascript">
function addfavo(state_name)
{
alert(state_name);
}
</script>
And in my html I have a loop (with php) which shows all the images with the add to favorite links which looks like.
<div style="margin-top:40px;">
<a onclick="addfavo('<?php echo $imgid ?>')"><b>Add to favourits</b></a>
</div>
So what happens is I have a lot of links to the same function with different parameters, but I only want the link that I click to change the text (to something like added to favorites)
Can some one help me in the right direction?
I have tried adding:
$(this).innerHTML("test");
but it didn't work.
You might want to use the html method:
$(this).html('test');
While html is a jQuery method, innerHTML is a property of a DOM element. If you were using pure JavaScript, you'd probably use:
this.innerHTML = 'test';
However, as you are using the onclick attribute on your HTML tag, this will not point to your current DOM element inside your function scope. In your case, I'd add a class to your elements, like add_favorite and add your text to another attribute:
<div style="margin-top:40px;">
<b>Add to favourits</b>
</div>
And then apply a jQuery event to it:
<script type="text/javascript">
$(function() {
$('.add-favorite').click(function(e) {
var text = $(this).data('text'); // store the text in a variable
$(this).html(text); // replace your element's html with your text
e.preventDefault();
});
});
</script>
Fiddle: http://jsfiddle.net/MH6vY/

Setting a JS variable and using it in html tag

I have set a variable, and I need to pull in this variable into a html element, but I cant get it to print out the value, this is the code:
<script>
var randomnumber=Math.floor(Math.random()*11)
</script>
<div id="<script type="text/javascript">document.write(randomnumber)</script>"></div>
Thanks.
Edit: I just used a div as an example, but i need to add a random number to an img tag, as it is for a tracking tag, and needs a unique identifier. Is there a better way to go about this?
Use
<script>
document.write('<div id="'+randomnumber+'" ></div>');
</script>
You can't open a script tag inside an attribute
Or you can create it using JS:
var randomnumber=Math.floor(Math.random()*11);
a = document.createElement('div');
a.setAttribute('id',randomnumber);
document.body.appendChild(a);
// if you know the exact class or ID where it is to be appended you can use
document.getElementsByClassName("myclass")[0].insertBefore(a, document.getElementsByClassName("beforeClass").firstChild);
This will create a div, with the id as the randomnumber and append it to the body

Need Solution on NicEdit Insert HTML text into Instance

i am using this function to insert text into NicEdit,
function insertAtCursor(editor, value){
var editor = nicEditors.findEditor(editor);
var range = editor.getRng();
var editorField = editor.selElm();
editorField.nodeValue = editorField.nodeValue.substring(0, range.startOffset) +
value +
editorField.nodeValue.substring(range.endOffset, editorField.nodeValue.length);}
This code works fine for simple text but when i pass HTML content into it, it does not render the HTML output in div instead it dumps the HTML code as it is into the Instance Div.
Example:
<div class="one">Some text here</div>
This must show in the Instance as "Some text here"
and remaining code hidden in source code.
Can any one give me a solution to fix this problem?
After working whole night and trying different solutions I had finally got it working! :)
In case any one wants to know solution for this, I had to add a Replace function
replace()
for the content and made it support HTML.
See my answer HERE. It's a plugin I created to insert html at the cursor position.

Categories