iswinky
iswinky

Reputation: 1969

JQuery - Replace quotes with html escape

A table shows data grabbed from a database on my site, when a button is clicked the "enableEditing" function is called using the onclick attribute. Then for one field for each row in the the table, an input textbox appears using the field as the value, and the key as the input name.

Before:

<tr class="data_row">
    <td class="property_cell">project ref</td>
    <td class="myNumber">200407</td>
</tr>

After:

<tr class="data_row">
    <td class="property_cell">project ref</td>
    <td class="myNumber">
        <input name="project ref" value="200407">
    </td>
</tr>

jQuery:

function enableEditing(){

    $("#object_data tr").each(function(){
        var key = $(this).children(".property_cell").html();
        var value = $(this).children(".myNumber").text();
        $(this).children(".myNumber").html("<input name='" + key + "' value='" + value + "'>");
    });
}

This works fine, however some of the data from the database contains speech marks or single quotes, which when changed to an input field will mess up the input html. How can I escape the html for each input field?

Upvotes: 2

Views: 1609

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388316

Try

$('.myNumber').contents().replaceWith(function(){
    return $('<input />', { name: $(this).parent().prev().text(), value : $(this).text()});
})

Demo: Fiddle

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324600

You should avoid using .html() for something like this. In fact, just don't use jQuery. Vanilla JS is vastly superior - jQuery is entirely built using it!

var rows = document.getElementById('object_data').rows, l = rows.length, i, td, inp;
for( i=0; i<l; i++) {
    td = rows[i].cells[1];
    if( !td.className.match(/\bmyNumber\b/)) continue; // failsafe
    inp = document.createElement('input');
    inp.type = "text";
    inp.name = rows[i].cells[0].firstChild.nodeValue;
    inp.value = td.firstChild.nodeValue;
    td.replaceChild(inp,td.firstChild);
}

While it may seem like more code, it will run at least an order of magnitude, possibly two or three, faster than the jQuery alternative.

jsFiddle
jsPerf

Upvotes: 0

Jan Kr&#252;ger
Jan Kr&#252;ger

Reputation: 18520

There are several ways. One of the less error-prone ones is to make jQuery/DOM do the escaping:

var input = $('<input name="'+key+'">');
input.val(value);
$(this).children(".myNumber").empty().append(input);

Upvotes: 3

Related Questions