jayz jayz - 1 month ago 5
Javascript Question

jQuery function - set String parameter

I am creating a web page and I want to give a alert whenever I clicked a row of the generated table that is generated by the below code. In order to do that I am using setAlert(message) function.
My problem is that it only works when the parameter that is set to the function is a integer. it doesn't work when it is a String.
Help me solve this problem.

Thank you.

function getItemList(){
$('#tableItem').empty();
$.ajax({
url: 'ItemServlet',
data:{version:2},
type: 'post',
dataType: 'json',
success: function (data) {
$('#tableItem').append('<table class="table table-striped table-hover" id="table1">\n\
<thead><tr><th class="table-text-align-centre" style="width:10%">Item Code</th>\n\
<th class="table-text-align-centre" style="width:20%">Name</th>\n\
<th class="table-text-align-centre" style="width:50%">Description</th>\n\
<th class="table-text-align-centre" style="width:10%">Stock Count</th>\n\
<th class="table-text-align-centre" style="width:10%">Active</th></tr></thead><tbody class="table-hover"></tbody></table>');
var length = data.length;
for (i = 0; i < length; i++) {
var post = data[i];
$('#table1').append('<tr onClick="setAlert('+post['itm_code']+')"><td>' + post['it_name'] + '</td>\n\
<td class="table-text-align-centre">' + post['itm_name'] + '</td>\n\
<td class="table-text-align-centre">' + post['itm_description'] + '</td> \n\
<td class="table-text-align-centre">' + post['itm_stockcount'] + '</td> \n\
<td class="table-text-align-centre">' + post['active'] + '</td> \n\
</tr>');
}
}
});
}



function setAlert(message) {
var id = message+ "";
alert(id);
}

Answer

The issue here is that you are passing your parameters into the setAlert function without defining the quotes. Now because you are using " to define your onClick and your using ' to formulate you html, you need to use an apostrophe escaped \' to pass in the parameter.

So currently, if post['itm_code'] is 1, it will generate the following html with valid javascript:

<tr onClick="setAlert(1)"><td>

However if post['itm_code'] is a string "my string", it will render the following html with invalid javascript:

<tr onClick="setAlert(my string)"><td>

So the following line:

<tr onClick="setAlert('+post['itm_code']+')"><td>

should be changed to:

<tr onClick="setAlert(\''+post['itm_code']+'\')"><td>
Comments