Random quotation mark being inserted into generated onclick html parameter - javascript

I'm trying to add parameters to an onclick function when generating HTML via javascript. When I inspect the code it is putting a quotation mark in the onclick function's parameter.
var lengthOfCats = ArrayOfCategories.length;
for (var a = 0; a < lengthOfCats; a++) {
$("#CatTable").append("<div class='better-table-cell'>" + ArrayOfCategories[a].Name + "</div>\
<div class='better-table-cell'>" + ArrayOfCategories[a].DepartmentName + "</div>\
<div class='better-table-cell'>" + ArrayOfCategories[a].Active + "</div>\
<div class='better-table-cell'>\
<button onclick=OpenUpdateCat(" + ArrayOfCategories[a].CategoryID + "," + ArrayOfCategories[a].Name + ");" + ">Edit</button>\
</div>");
Here is an image of the HTML that is getting generated for the edit button.

The browser is normalising the HTML and putting quote marks around the attribute value.
The problem is that because the attribute value includes spaces, and you didn't put the quote marks in the right spots yourself, the attribute value finishes in the middle of the JavaScript.
The next bit of JS is then treated as a new attribute.
Mashing together strings to generate HTML is fundamentally a bad idea. Ensuring all the right things are quoted and escaped is hard.
Use DOM to generate your HTML instead.
It is a little longer, but clearer and easier to maintain in the long run.
var $cat_table = $("#CatTable");
var lengthOfCats = ArrayOfCategories.length;
for (var a = 0; a < lengthOfCats; a++) {
$cat_table.append(
$("<div />").addClass("better-table-cell").text(ArrayOfCategories[a].Name)
);
$cat_table.append(
$("<div />").addClass("better-table-cell").text(ArrayOfCategories[a].DepartmentName)
);
$cat_table.append(
$("<div />").addClass("better-table-cell").text(ArrayOfCategories[a].Active)
);
$cat_table.append(
$("<div />").addClass("better-table-cell").append(
$("<button />").text("Edit").on("click", generate_edit_handler(ArrayOfCategories[a].CategoryID, ArrayOfCategories[a].Name))
)
);
}
function generate_edit_handler(cat_id, name) {
return function () {
OpenUpdateCat(cat_id, name);
};
}

Related

Passing argument to on click event of dynamically generated element

I am trying to pass arguments to onclick event of dynamically generated element. I have already seen the existing stackoveflow questions but it didn't answer my specific need.In this existing question , they are trying to access data using $(this).text(); but I can't use this in my example.
Click event doesn't work on dynamically generated elements
In below code snippet, I am trying to pass program and macroVal to onclick event but it doesn't work.
onClickTest = function(text, type) {
if(text != ""){
// The HTML that will be returned
var program = this.buffer.program;
var out = "<span class=\"";
out += type + " consolas-text";
if (type === "macro" && program) {
var macroVal = text.substring(1, text.length-1);
out += " macro1 program='" + program + "' macroVal='" + macroVal + "'";
}
out += "\">";
out += text;
out += "</span>";
console.log("out " + out);
$("p").on("click" , "span.macro1" , function(e)
{
BqlUtil.myFunction(program, macroVal);
});
}else{
var out = text;
}
return out;
};
console.log of out give me this
<span class="macro consolas-text macro1 program='test1' macroVal='test2'">{TEST}</span>
I have tried both this.program and program but it doesn't work.
Obtain values of span element attributes, since you include them in html:
$("p").on("click" , "span.macro" , function(e)
{
BqlUtil.myFunction(this.getAttribute("program"),
this.getAttribute("macroVal"));
});
There are, however, several things wrong in your code.
you specify class attribute twice in html assigned to out,
single quotes you use are not correct (use ', not ’),
quotes of attribute values are messed up: consistently use either single or double quotes for attribute values
var out = "<span class='";
...
out += "' class='macro' program='" + program + "' macroVal='" + macroVal + ;
...
out += "'>";
depending on how many times you plan to call onClickTest, you may end up with multiple click event handlers for p span.macro.

Dynamically add array contents as new elements - JQuery

edit: Problem solved! I was modifying the page before it was loaded so the script didn't actually do anything. I fixed it now and it works. Thanks for the help, I'll have to chalk this one up to being new to jQuery and it's weirdness.
Long story short I'm trying to make a webpage that dynamically takes Article titles, thumbnail images, descriptions, and links to them, and creates a nicely formatted list on the page. I'm trying to accomplish this in jQuery and HTML5.
Here is the sample data that I'll be using to dynamically populate the page. For now formatting isn't important as I can do that later after it works at all.
<script>
var newsTitles = ["If It Ain't Broke, Fix It Anyways"];
var newsPics = ["images/thumbnail_small.png"];
var newsDescs = ["August 14th 2015<br/><b>If It Ain't Broke</b><br/>Author: Gill Yurick<br/><br/> Sometimes, a solution isn't the only one. So how do we justify changes to systems that don't need to be fixed or changed? I explore various systems from other successful card games and how their approaches to issues (be they successes or failures in the eyes of the deisgners) can help us create EC."];
var newsLinks = ["it_aint_broke-gill_popson.html"];
var newsIndex = 0;
var newsMax = 1;
The section of code where I'm trying to use the contents of the arrays above to dynamically fill elements.
<td style="height:500px;width:480px;background-color:#FFF7D7;padding:20px" colspan=2 id="article">
<h1>Articles</h1>
<!-- the column for each news peice add an element with the thumbnail, the title and teh desc -->
<script>
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href="" newsLinks[i] + "">" + newsTitles[i] + "</h3>", "<img src=""newsPics[i] + "">","<p>" + newsDesc[i] + "</p>", ); $("div").append("hello");
}
</script>
<div id="articleList">
HELLO
</div>
</td>
Here is what it ends up looking like, I can post more info if needed as I am aware this may not be clear enough to fully explain my problem but I am unable to determine that. Thank you in advance.
try this
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href=""+ newsLinks[i] + "">" + newsTitles[i] + "</h3>, <img src=""+newsPics[i] + "">, <p>" + newsDescs[i] + "</p>" ); $("div").append("hello");
}
Concatation issue + typo for newsDescs
The following string is invalid html and is missing a +
"<h3 href="" newsLinks[i] + "">"
You need to use proper quotes for html attributes, not &quote;
Try
"<h3 href='" + newsLinks[i] + "'>"
OR
"<h3 href=\"" + newsLinks[i] + "\">" // `\` used to escape same type quote
Personally I prefer opening/closing html strings with single quotes but either will work
Note tht you should be getting a syntax error thrown in dev tools console which would have helped you locate problems
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href='" + newsLinks[i] + "'>" + newsTitles[i] + "</h3>");
$("#articleList").append("<img src='" + newsPics[i] + "'>","<p>" + newsDesc[i] + "</p>" );
}

edit (append?) a string stored in a jquery variable

I am bringing a big html string inside an ajax call that I want to modify before I use it on the page. I am wondering if it is possible to edit the string if i store it in a variable then use the newly edited string. In the success of the ajax call this is what I do :
$.each(data.arrangement, function() {
var strHere = "";
strHere = this.htmlContent;
//add new content into strHere here
var content = "<li id=" + this.id + ">" + strHere + "</li>";
htmlContent is the key for the chunk of html code I am storing in the string. It has no problem storing the string (I checked with an alert), but the issue is I need to target a div within the stored string called .widgteFooter, and then add some extra html into that (2 small divs). Is this possible with jquery?
Thanks
Convert the string into DOM elements:
domHere = $("<div>" + strHere + "</div>");
Then you can update this DOM with:
$(".widgetFooter", domHere).append("<div>...</div><div>...</div>");
Then do:
var content = "<li id=" + this.id + ">" + domHere.html() + "</li>";
An alternative way to #Barmar's would be:
var domHere = $('<div/>').html( strHere ).find('.widgetFooter')
.append('<div>....</div>');
Then finish with:
var content = '<li id="' + this.id + '">' + domHere.html() + '</li>';
You can manipulate the string, but in this case it's easier to create elements from it and then manipulate the elements:
var elements = $(this.htmlContent);
elements.find('.widgteFooter').append('<div>small</div><div>divs</div>');
Then put the elements in a list element instead of concatenating strings:
var item = $('<li>').attr('id', this.id).append(elements);
Now you can append the list element wherever you did previously append the string. (There is no point in turning into a string only to turn it into elements again.) Example:
$('#MyList').append(item);

How do I get these HTML tags to render from javascript

Noob question alert! So, I've got this script, which loops through an array and adds a <br> tag to the end of each array item. But i dont know the proper way of displaying this output on my page. Currently, when it loads the <br> tags show up on screen, whereas I want them to render as line-breaks. It is outputting into a <textarea> if that makes a difference. Thanks a bunch.
var outputLinkText = document.getElementById('outputLinkText');
var outputStageOne = "";
for (var i = 0; i < arrayOne.length; i++) {
outputStageOne += (arrayOne[i] + "<br>");
}
if ( 'textContent' in timePlace ) {
outputLinkText.textContent = outputStageOne;
}
else {
outputLinkText.innerText = outputStageOne;
}
<textarea> tags don't support <br> tags (or any other HTML tags) within their contents. They only hold plain text.
You need to add "\n" as the separator instead.
(Strictly, it should be "\r\n" but a "\n" on its own is usually sufficient)
Yes the textarea is a difference, try this :
"\r\n" instead of "<br>"

How do I insert a space before and after the content of a DOM element?

If i have
<p>someword here</p>
<span>another thing here</span>
<div id="text">other thing here</div>
<!-- any other html tags -->
How do I insert a space in first and last position of the content?
I want the result to be
<p> someword here </p>
<span> another thing here </span>
<div id="text"> other thing here </div>
<!-- after tags like <p> and before </p> there have one space -->
Naive (and incorrect!) example would be:
var victims = document.querySelectorAll('body *');
for( var i = 0; i < victims.length; i++ ) {
victims[i].innerHTML = " " + victims[i].innerHTML + " ";
}
But once you run it, you will find out that all your elements got destroyed! Because, when you are changing innerHTML, you are changing element children as well. But we can avoid that, by not replacing content, but adding it:
var padLeft = document.createTextNode( " " );
var padRight = document.createTextNode( " " );
victims[i].appendChild( padRight );
victims[i].insertBefore( padLeft, victims[i].firstChild );
Looks cool! But, o no - we ruin our script tags, images and so on. Lets fix that too:
var victims = document.querySelectorAll('body *');
for( var i = 0; i < victims.length; i++ ) {
if( victims[i].hasChildNodes ) {
var padLeft = document.createTextNode( " " );
var padRight = document.createTextNode( " " );
victims[i].appendChild( padRight );
victims[i].insertBefore( padLeft, victims[i].firstChild );
}
}
Here you got the script :) Its not cross-browser all the way down to Netscape4, but is enough to understand basic idea.
If you insist using JS + RegExp to pad every element's innerHTML then you could do:
var
r = /(<[^>]+>)(.*)(<\/[^>]+>)/g,
func = function(str) {
return str.replace(r, function(original, a, b, c) {
return a + ' ' + (r.test(b) ? func(b) : b) + ' ' + c;
});
};
func("<p name='somename'>someword here</p>");
// "<p name='somename'> someword here </p>"
func("<div>I have things here<span>And more here<p>And even more here</p></span></div>");
// "<div> I have things here<span> And more here<p> And even more here </p> </span> </div>"
This is just to show how you could do this, but I highly recommend against it. The examples I provide is extremely simple. Anything like a normal page (say, the one you are looking at now) has all sorts of tags. This would be extremely exhaustive. And not very wise.
For a single element (as you seem to be asking):
element.html(' ' + element.html() + ' ')
For every element on the page (as your example seems to indicate), apply that to each element.
With jQuery*:
$('#id').html(' ' + $('#id').html() + ' ');
If you know that the elements do not have nested elements, it would be better to use the simpler:
$('#id').text(' ' + $('#id').text() + ' ');
(*) The reason for using jQuery and not plain javascript is that browsers (I'm looking at you, IE), have different inbuilt properties for getting and setting these values. jQuery saves you from having to worry about that.
in your case:
$("*").html(function(index, html){ return " " + html + " "; });

Categories