Escaping quotes in jquery - javascript

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.

Related

Dynamically added textbox with given value not added properly,jquery

I added textbox value as Baker's Basket, Pune, Maharashtra, Indiasd but on click event in textbox it only shows Baker's
I want to display whole text Baker's Basket, Pune, Maharashtra, Indiasd in the textbox.
JS FIDDLE EXAMPLE
// Try to Enter text given bellow
//Baker's Basket, Pune, Maharashtra, Indiasd
$("#clk").on('click', function () {
$("#cnt_div").empty();
var getTxt = $("#txt_n").val();
var addContent = "<input type='text' value=" + getTxt + " />";
$("#cnt_div").append(addContent);
});
without editng addContent variable
Edited:
JS FIDDLE SAMPLE TWO
$("#clk").on('click', function () {
var gData1 = $("#txt_1").val();
var gData2 = $("#txt_2").val();
var gData3 = $("#txt_3").val();
var cnt_1 = "<span class='lbl_normal_mode'>" + gData1 + "</span><input class='txt_edit_mode' value=" + gData1 + " type='text'/>";
var cnt_2 = "<span class='lbl_normal_mode'>" + gData2 + "</span><input class='txt_edit_mode' value=" + gData2 + " type='text'/>";
var cnt_3 = "<span class='lbl_normal_mode'>" + gData3 + "</span><input class='txt_edit_mode' value=" + gData3 + " type='text'/>";
var content_Data = "<div class='chunk_div_holder'><div style='float:left:width:100%'>" + cnt_1 + "</div><div style='float:left:width:100%'>" + cnt_2 + "</div><div style='float:left:width:100%'>" + cnt_3 + "</div></div>";
$(".dynmic_cntt").append(content_Data);
});
You should better append the element and its properties dynamically as an object:
$('<input>', {
type: 'text',
value: $("#txt_n").val()
}).appendTo($("#cnt_div").empty());
This will solve the problem of extra spaces (no quotes for value=Baker's Basket), wrong string escape (if the value will have quotes) for value attribute and other caveats.
N.B.: There is no textbox type for <input> element. It should be text instead.
DEMO: http://jsfiddle.net/ZyMCk/11/
Add the field in two stages:
add the field as you are already
set the value of the field using .val()
It is because you aren't escaping ' single quote.
Instead you can replace
this line
var addContent="<input type='textbox' value='"+getTxt+"' />";
with
var addContent=$("<input type='textbox' />").val(getTxt);
or
var addContent="<input type='textbox' value=\""+getTxt+"\" />";
Value attribute should enclose in quotes. In your case, its better to use double quotes, because Baker's Basket, Pune, Maharashtra, Indiasd already have a single quote in it.
$("#clk").on('click',function(){
$("#cnt_div").empty();
var getTxt=$("#txt_n").val();
var addContent="<input type='textbox' value=\""+getTxt+"\" />";
$("#cnt_div").append(addContent);
});
Fiddle
Edit
$("#clk").on('click',function(){
$("#cnt_div").empty();
var getTxt=$("#txt_n").val();
var addContent=$("<input/>",{type:"text",value:getTxt});
$("#cnt_div").append(addContent);
});
Updated fiddle
change "+getTxt+" to '"+getTxt+"'
fiddle
OR
change "+getTxt+" to \""+getTxt+"\"
Heres a better way of doing this...
var addContent=$("<input type='textbox' />").val(getTxt);
http://jsfiddle.net/ZyMCk/9/
Basically, if creating an element to append to the DOM your better off doing this as a jQuery object. This way we can take advantage of methods such as val() for adding the value.
UPDATE
Ive simplified things a bit for you...
JSFIDDLE: http://jsfiddle.net/ZyMCk/22/
$("#clk").on('click', function () {
$('.dynmic_cntt').empty();
$('.form-text').each(function(){
var $div = $('<div style="float:left:width:100%;"></div>');
var $span = $('<span class="lbl_normal_mode">'+ $(this).val() +'</span><input class="txt_edit_mode" value="'+$(this).val() +'" type="text"/>');
$('.dynmic_cntt').append( $div.append( $span ) );
});
});

attempting to split string dynamically keep getting error?

I'm attempting to split a string I'm passing into
$("#groupUL").append("<li>" + "<h2>About Item:</h2> " + response.data[i].message + "<br /> " + "<h2>Posted By:</h2> <a href='#' onclick='splitName('" + response.data[i].from.name + "');'>" + response.data[i].from.name + "</a>" + "<br />");
Seems to be passing me the error
SyntaxError: syntax error
splitName(
Not sure how that's wrong...Here is the splitname function if that helps
function splitName(txt){
var myString = txt;
var mySplitResult = myString.split(" ");
console.log("The first element is " + mySplitResult[0]);
console.log("<br /> The second element is " + mySplitResult[1]);
console.log("<br /> The third element is " + mySplitResult[2]);
};
It's too hard to get it right when you put quotes in quotes in quotes and you try to escape it right. You got it wrong.
A solution is to make it in small parts :
var action = "splitName('" + response.data[i].from.name + "');";
$("#groupUL").append("<li>" + "<h2>About ... onclick=\""+action+"\">...");
But the best solution would be to follow best practice, that is not inline the javascript but use jQuery's binding function :
$("#groupUL").append("... <a id=myid ...");
$("#myid").click(function(){ splitName(response.data[i].from.name) });
I think the only problem with your code is with your readability issue. So I would suggest please improve it. Lets have a look at it. My code example # JSbin.
Here is the code :- (which i think is better)
var response = {
data : {
message: 'Cleaning code',
from: {
name: 'Clean Code works'
}
}
};
var li = $('<li>'); //Create empty li (Not Appending to DOM now due to performance issues)
$('<h2>').html('About Item:' + response.data.message + '<br />').appendTo(li);
$('<h2>').html('Posted By:').appendTo(li);
$('<a>').attr('href', '#')
.html(response.data.from.name)
.appendTo(li)
.click(function() {
splitName(response.data.from.name);
});
$('<br>').appendTo(li);
// Append li to ul (Final operation to DOM)
li.appendTo('#groupUL');
function splitName(txt){
var myString = txt;
var mySplitResult = myString.split(" ");
console.log("The first element is " + mySplitResult[0]);
console.log("The second element is " + mySplitResult[1]);
console.log("The third element is " + mySplitResult[2]);
}

error in adding class to a pargraph element which is defined inside document.write() of javascript

this is my js code-
var str1 = "Wardrobe Makeover";
var str2 = "Female Fashion Makeover";
var str3 = "Male Fashion Makeover";
var menu1=new Array()
menu1[0]= document.write("<p>" + str2.link("http://abc.com/mystylemuse/wardrobe_makeover") + "</p>");
menu1[1]= document.write("<p>" + str2.link("http://abc.com/mystylemuse/female") + "</p>");
menu1[2]= document.write("<p>" + str3.link("http://abc.com/mystylemuse/male") + "</p>");
whenever i add a css class name inside <p>, like- document.write("<p class="abc">" + str2.link("http://abc.com/mystylemuse/wardrobe_makeover") + "</p>"); it shows error. please tell me how can i add a class inside <p> element.
It should be:
document.write("<p class=\"abc\">" + str2.link("http://abc.com/mystylemuse/wardrobe_makeover") + "</p>");
If your string includes double quotes, then you can use single quotes as string delimiters, and vice versa.
'<p class="abc">'
or
"<p class='abc'>"

Are there any string formatting functions built into jQuery?

I have the following code:
$("#stats-list")
.append("<li>Elapsed: " + ajaxElapsed + "</li>\n" +
"<li>Display: " + tableElapsed + "</li>\n" +
"<li>Total: " + (ajaxElapsed + tableElapsed) + "</li>");
This was originally three appends that I concatenated into one. Is there anything I could do with jQuery that would clean up this code even more. What I was wondering was if jQuery has any string formatting with tokens that I could use.
function format(formatString) {
var args = Array.prototype.slice.call(arguments,1);
return formatString.replace(/\{(\d+)\}/g, function(match, num) {
return args[Number(num)];
});
}
format("<li>Elapsed: {0}</li>\n<li>Display: {1}</li>\n<li>Total: {2}</li>",
ajaxElapsed, tableElapsed, ajaxElapsed + tableElapsed);
afaik there is none built-in, but a powerful templating-subsystem, see jQuery Templates
just for completeness, i think this could be done more elegant:
var list = $('#stats-list');
$('<li />').text('Elapsed: ' + ajaxElapsed).appendTo(list);
$('<li />').text('Display: ' + tableElapsed).appendTo(list);
$('<li />').text('Total: ' + (ajaxElapsed + tableElapsed)).appendTo(list);
If you have many items you can do something like this to avoid missing + and writing li so many times. You can add any number of items inside the array and they will be joined with lis appropriately.
var list = '<li>' + [
'Elapsed: ' + ajaxElapsed,
'Display: ' + tableElapsed,
'Total: ' + ajaxElapsed + tableElapsed
].join('</li><li>') + '</li>';
$("#stats-list").append(list);
As a note I wouldn't use \n. li is a block element by default, so you'd be better styling it with css.

WHy Doesnt This Javascript Function Work

What I'm trying to do here is make one function that does all the functionality for a custom select element. So I made a function that accepts three parameters which are defined in the function itself (see code below for more detail). I'm trying to accomplish the following: I want the parameters to be the IDs of the various elements (the wrapper div for example), and I want those parameters to be dropped in the function. My Code is below. Thanks so much
function createList(ParentDivID,SelectMenuID,ListMenuID) {
$('#' + ParentDivID + "'");
$('#' + SelectMenuID + "'");
$('#' + ListMenuID + "'");
var options = $("#" + SelectMenuID +'"' ).find("option");
$(options).each(function(){
$(ul).append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
var ul = '<ul id="' + ListMenuID + "></ul>";
$('#' + ParentDivID + "'").append(ul).end().children('#' + ListMenuID + "'").hide().click(function(){$(ul).slideToggle();});
$("#" + SelectMenuID + '"').hide();
}
createList(fancySelectLarge,selectWalkerType,walkerTypeLi);
At a guess, it is probably because your ids don't end in quote characters (which aren't allowed in ids in HTML 4), but you are appending them to the strings you are searching for with jQuery.
You only need to do your selectors like this
$('#' + ParentDivID);
Also you need to stop interchanging 's and "s because it is causing you to miss some closing quotes
function createList(ParentDivID,SelectMenuID,ListMenuID) {
var options = $('#' + SelectMenuID).find('option');
$(options).each(function(){
$(ul).append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
var ul = '<ul id="' + ListMenuID + '"></ul>';
$('#' + ParentDivID).append(ul).end().children('#' + ListMenuID).hide().click(function(){$(ul).slideToggle();});
$('#' + SelectMenuID).hide();
}
createList(fancySelectLarge,selectWalkerType,walkerTypeLi); `
You are messing up all of your string concatenations like:
$('#' + ParentDivID + "'"); should be $('#' + ParentDivID);
It's generally a bit of a mess but I've tried to fix as much as possible.
function createList(ParentDivID,SelectMenuID,ListMenuID) {
var options = $("#" + SelectMenuID).find("option");
var ul = $('<ul>', {id: ListMenuID});
$(options).each(function(){
ul.append('<li>' +
$(this).text() + '<span class="value">' +
$(this).val() + '</span></li>');
});
$('#' + ParentDivID)
.append(ul)
.end()
.children('#' + ListMenuID)
.hide()
.click(function() { ul.slideToggle(); });
$("#" + SelectMenuID).hide();
}
When you call the function, are the three parameters already variables assigned elsewhere in your code? If not, and the are actually the string id attributes, you need to enclose them in quotes.
createList("fancySelectLarge", "selectWalkerType", "walkerTypeLi");
Note: See other valuable responses about the incorrect quoting in $('#' + ParentDivID + "'");
$(ul) is undefined when execution reaches it, because var ul is only declared a few lines later on. You will also need to use document.body.createElement('ul') instead of putting '<ul ...>' in a string.
Also, the lines $('#' + ParentDivID + "'"); don't do anything.
You need to define ul before using it. Also, define it as $('<ul.../>') not just '<ul.../>', so that you can create a jQuery element from that definition.
and you want also try to create the dom element like this
$('<span class="value">') instead of a string value '<span class="value">'.

Categories

Resources