Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to escape quotes in while creating a textbox in jquery / javascript?

I have a couple of span elements and I need to get the contents of these span elements into a textbox so the user can edit.

There might be any number of span elements, so the textboxes have to be created at runtime. The problem I'm having is that when the text contains a single quotes, it's messing with my text box values since it closes one of the quotes..

This is how I am creating my textbox:

var spanContent = $(value).text();
var tmpTextBox = "<input type='text' id='t" + index + "' value='" + spanContent  + "' class='dynTxt' />";

Notice the value='" + spanContent + "' part, this is where it's breaking if spanContent has a single quote in it.. Now, I know I can do this:

value = \"" + spanContent + "\"

which works fine.. but, when the spanContent has double quotes, it breaks again..

What is the safest way to escape both single quotes and double quotes in this situation, please? I cannot html encode them because textbox values doesn't support them..

I have created a small reproduction of this on jsfiddle here for you to play with..

Thanks.

like image 528
LocustHorde Avatar asked Jan 12 '12 14:01

LocustHorde


1 Answers

For starters, if you're using jQuery take advantage of how modular it can be when creating elements. Not only is writing out the HTML elements bad from a security perspective, it's also prone to errors (as you've established). However, you'll be happy to know there is always a better way:

var input = $('<input />',{
  'type': 'text',
  'id': 't'+index,
  'value': spanContent,
  'class': 'dynTxt'
});

Now you have a new <input> element that can be attached, manipulated, etc. You can also do it the "long" way:

var input = $('<input />')
  .attr({'type':'text','id':'t'+index})
  .val(spanContent)
  .addClass('dynTxt');

Which results in the same element being generated:

<input type="text" id="t_index_" value="_spanContent_" class="dynTxt" />

The best part is that any problems (like quotes) will be solved for you, leaving you to just write the content you need.

like image 104
Brad Christie Avatar answered Nov 15 '22 00:11

Brad Christie