Building html tag with javascript - javascript

The scenario is the following:
I call the buldMyStuff function to build images many times the following way. Wrapping the img into an "a" tag is not an option.
function buildMyStuff(item){
var tag = <img src="someimg.png" onclick="doClick(' + item.Type + ',' + item.data+ ')" />';
return tag;
}
function doClick(type,data){
//do stuff
}
Lets assume that the item.type value is "type" and the item.data value is "data".
The problem with this that when I click the image it says type is not defined. Therefore (and I checked in the built html structure) the img eventually looks like this:
<img src="someimg.png" onclick="doClick(type,data)" />
What I need to achieve is:
<img src="someimg.png" onclick="doClick('type','data')" />
However as I am using the ' character to wrap the whole tag and the " character to wrap the attribute I cannot use anything else. Does someone know the solution for this?
Thank you in advance.

You can use '\' to escape special characters.
var tag = <img src="someimg.png" onclick="doClick(' + item.Type + ',' + item.data+ ')" />';
=>
var tag = '<img src="someimg.png" onclick="doClick(\'' + item.Type + '\',\'' + item.data+ '\')" />';

this is invalid;
var tag = <img src="someimg.png" onclick="doClick(' + item.Type + ',' + item.data+ ')" />';
It should be
var tag = '<img src="someimg.png" onclick="doClick(\'' + item.Type + '\',\'' + item.data+ '\')" />';

function buildMyStuff(item){
var tag = '<img src="someimg.png" onclick="doClick(\'' + item.Type + '\',\'' + item.data+ '\')" />';
return tag;
}

Related

How do I Get Text from Dynamically created element in JavaScript

I am dynamically creating Div Text in JS and was wondering how I access the various text upon click.
Here is what I have tried so far;
My Dynamically created div
function Message(Side, message) {
var divChat = '<div class="direct-chat-msg ' + Side + '">' +
'<div id="myDiv" class="direct-chat-text">' + message + '</div>' +
'<div id="accountMenu">' +
'<li onclick = "getMessage(' + message + ')" id="replyDiv">Reply</li>' +
'<li>Preferences</li>' +
'</ul>' +
'</div></div>';
$('#divChatWindow').append(divChat);
}
JS when the li is clicked on.
function getMessage(str) {
alert(str);
}
The error I am getting is:
Uncaught ReferenceError: *whaeverthemessageis* is not defined
at HTMLLIElement.onclick
What is the best solution to solve this problem?
Thanks =)
You have malformed html using single and double quotes. The message is being treated as a variable, not a string, hence the undefined error.
replace:
'<li onclick = "getMessage(' + message + ')" id="replyDiv">Reply</li>' +
with this:
'<li onclick = "getMessage(\'' + message + '\')" id="replyDiv">Reply</li>' +
I'm not exactly sure what the problem is, but here is a working Playcode

CSS Style not being applied in Javascript

If I have the following html added statically the CSS style is applied correctly
HTML:
<li class="connector">
<a href="#">
<img src="css/images/temp/connector2.png" alt="" width="192" height="192">
<span class="sr-only">box</span>
</a>
</li>
However if I do the following in Javascript to dynamically render the HTML the CSS does not seem to get applied.
JavaScript:
element.innerHTML += "<li class='connector'>" +
"<a href = '/connector/" + i + "'>" +
"<img src ='/" + i + "/background' />" +
"<span class='sr-only'>" + $.get("/" + i + "/getName") +"</span>" +
"</a>" +
"</li>";
The list shows, but without the CSS styling.
Any suggestions?
"<span class='sr-only'>" + $.get("/" + i + "/getName") +"</span>" +
get is asynchronous method. This addition is wrong.
The problem was with how I was using the Isotope Javascript library. The way I was adding the content was bypassing it.
After reading their documentation, I was able to get it to work properly.
I used the following instead
$.get("/connectorCount", function(data){
for (var i = 0; i < data; i++)
{
var $newItems = $('<li class="connector"> <img src = "/' + i + '/background" /> <span class="sr-only">' + $.get("/" + i + "/getName") + '</span></li>');
$('.connectors').isotope('insert', $newItems);
}
refreshSearch(data);
});

Add image and text to list in html from JSON

My use case is to add image and a text dynamically to list. All I have is JSON (extracted from DB as result set). The JSON structure is as mentioned below:
[{"Comment":"Test","FilePath":"\/storage\/sdcard0\/20130725153841.JPEG"},{"Comment":"Image List","FilePath":"\/storage\/sdcard0\/20130725160020.JPEG"}]
So, in my java script, I append this list to a HTML body through the following code:
<script>
$(document).ready(function(e) {
var data = [{"Comment":"Test","FilePath":"\/storage\/sdcard0\/20130725153841.JPEG"},{"Comment":"Image List","FilePath":"\/storage\/sdcard0\/20130725160020.JPEG"}]
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val.Comment + '</li>');
});
$('<ul/>', {
html: items.join('')
}).appendTo('body');
});
</script>
Here, I am trying to bring an image (whose filepath is available in the JSON) to the list. So, the list should contain image (may be a smaller one - I shall use styling for this) and the comment side by side.
Please can someone help?
EDIT:
I tried this: I am building the list runtime.. So, i tried using
before val.comment.. it doesnt seem to work. Any words on this?
In order to show image with each list item you should have to add img tag in your list item. The JS code should be like below:
items.push('<li id="' + key + '"><img src="' + val.FilePath + '" />' + val.Comment + '</li>');
Hope this will help !!
In your items.push add the <img> tag and output the value from your FilePath field:
items.push('<li id="' + key + '">' + val.Comment + '<img src="' + val.FilePath +'" alt="" />' + '</li>');

Passing a js var into jquery action as attribute

var temp="path.png"
How can I pass temp var into the jquery function as shown below
$('#mapfoto').prepend('<img id="theImg" src="http://path.gr/"+temp />')
Use correct quotes placement in string concatenation:
$('#mapfoto').prepend('<img id="theImg" src="http://path.gr/' + temp + '" />');
$('#mapfoto').prepend('<img id="theImg" src="http://path.gr/' + temp + '" />');

Escaping quotes in jquery

I'm having a bit of a problem escaping quotes in the following example:
var newId = "New Id number for this line";
$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="runFunction("#my' + newId + '");"></td>');
The issue is that when I look at the generated code the id does update to id="myNewId", but in the function call it looks like this:
onkeyup="runFunction(" #row2="" );=""
What exactly am I doing wrong?
Just don't put JavaScript into the HTML string:
$(id).html(
'<td><input type="text" id="my' + newId + '"></td>'
).find("input").keyup( function() {
runFunction("#my" + newId);
});
Thinking about it, in this special case you can exchange the keyup() function body for:
runFunction(this);
because you seem to want to run the function on the object itself.
You need to use HTML character references for HTML attribute values. Try this:
function htmlEncode(str) {
var map = {"&":"amp", "<":"lt", ">":"gt", '"':"quot", "'":"#39"};
return str.replace(/[&<>"']/g, function(match) { return "&" + map[match] + ";"; });
}
$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="' + htmlEncode('runFunction("#my' + newId + '");') + '"></td>');
You forgot to escape the attribute's quotes.
var newId = "New Id number for this line";
$(id).html('<td><input type="text" id="my' + newId + '" onKeyUp="runFunction(\'#my' + newId + '\');"></td>');
You should use escaped single quotes \' to surround the #my... part.

Categories

Resources