I have built a function using jQuery to insert into a table a new row including some inputs, like textboxes, checkboxes and one button.
This is the code I have:
$('#AddEntry').click(function () {
var lastTrClass = $('tr:last').attr('class');
var textBoxTitle = '<input id="titleid" type="text" value="" style="width: 100%; vertical-align: middle">';
var textBoxStartDate = '<input id="StartDate" type="text" class="required DatePicker" value="" style="width: 100%; vertical-align: middle">';
var checkBoxSync = '<input id="Sync" type="checkbox" checked="checked" disabled="disabled" value="true" style="vertical-align: middle">';
var lastDate = '<input id="LastSyncDate" class="required DatePicker" type="text" value="" style="width: 100%; vertical-align: middle">';
var buttonEdit = '<button id="btnEditar" class="EditButton icon_only text_only" style="vertical-align: middle;" type="button">Editar</button>';
if (lastTrClass == 'gradeA odd') {
$('#DataTable > tbody:last').append("<tr class='gradeA even'><td>#</td><td>" + textBoxTitle + "</td><td>" + textBoxStartDate + "</td><td>" + checkBoxSync + "</td><td>" + lastDate + "</td><td>" + buttonEdit + "</td></tr>");
}
else {
$('#DataTable > tbody:last').append("<tr class='gradeA odd'><td>#</td><td>" + textBoxTitle + "</td><td>" + textBoxStartDate + "</td><td>" + checkBoxSync + "</td><td>" + lastDate + "</td><td>" + buttonEdit + "</td></tr>");
}
})
As you can see in my code, I’m generating the inputs into a var, but my question is whether or not this is safe. Is my code vulnerable to a JS injection or something like that? Is there a better way to do this?
All of this happens on the client so you’re code should be fine. You may want to check out client templating for this sort of thing though – then you can scrap the vars altogether and editing the html will be more pleasurable. I use jqote when I need to render relatively complex stuff from javascript.