简体   繁体   中英

jQuery: td content with single quotes gets cut off when being passed to modal

I have a page with a dynamic HTML table. One column there is called " itemName " and contains text that can also include quotes.

Example:

<td class='itemName'>Collector's Edition</td>

The table has some buttons that create a modal and pass some table content to the modal on the fly.

Example:

<input type='text' class='form-control' id='itemName' value='" + $(this).closest('tr').find('.itemName').text() + "' />

Everything works as intended. My only problem is that whenever the td content contains a single quote then the text that is passed to the modal appears cut off, eg in the above example it would only pass Collector.

How can I avoid this in jQuery ?

After trying on this problem, i came to see that when you do like this:

$('span').after("<input type='text' value='"+$("span").text()+"'/>")

as span's text had single quote so it considers it as closing of code and closes it there.

But it we write it like this, it works:

$('span').after('<input type="text" value="'+$("span").text()+'"/>')

FIDDLE SAMPLE:

http://jsfiddle.net/arjpdkv1/1/

UPDATED:

If the text contains double quotes then this code will also fail, more better way is to create elements this way not by appending string html, now this does not matter that the span text contains single quotes or double quotes:

$('span').after($('<input/>').attr({
type: 'text',
value: $("span").text()
}));

DEMO FIDDLE

please replace your code with this. It will escape your single quote character and it will work fine.

var html = "<input type='text' class='form-control' id='itemName' value='" +
    $(this).closest('tr').find('.itemName').text().replace("'","&#39;") + "' />";

JS FIDDLE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM