Ajax Callback to append a select dropdown html to table? - javascript

I am trying to append some html using jQuery using below code. This whole thing i am just trying to select an option using ajax response data and building a select dropdown. But sOut variable scope not able to persist appended html inside callback function looping. Is there any work around to achieve what i am doing?
getVendor(aData[2], function (response) {
var obj = jQuery.parseJSON(response);
var sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
var industries_select = '<tr><td>Industry:</td><td><select class="form-control m-bot15">';
getIndustries(function (response) {
var industries = jQuery.parseJSON(response);
for (var l = 0; l < industries.length; l++) {
if (industries[l].id == obj.industry) {
industries_select += '<option value="' + industries[l].id + '" selected="selected">' + industries[l].name + '</option>'
} else {
industries_select += '<option value="' + industries[l].id + '">' + industries[l].name + '</option>'
}
}
});
industries_select += '</select></td></tr>';
sOut += industries_select;
sOut += '</table>';
});

That's the expected behavior of async request. you should be doing something like this
getVendor(aData[2], function (response) {
var obj = jQuery.parseJSON(response);
var sOut = '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">';
var industries_select = '<tr><td>Industry:</td><td><select class="form-control m-bot15">';
getIndustries(function (response) {
var industries = jQuery.parseJSON(response);
for (var l = 0; l < industries.length; l++) {
if (industries[l].id == obj.industry) {
industries_select += '<option value="' + industries[l].id + '" selected="selected">' + industries[l].name + '</option>'
} else {
industries_select += '<option value="' + industries[l].id + '">' + industries[l].name + '</option>'
}
}
industries_select += '</select></td></tr>';
sOut += industries_select;
sOut += '</table>';
});
});
Because, the callback of getIndustries will be called later point in time, and when the time you access industries_select outside the function, it's undefined.

If, for example, you're building the HTML dynamically then you may try appending the sOut variable to a Div tag inside your function scope, for example:
HTML:
<div id="dynamic"></div>
JQuery:
$("#dynamic").append(sOut);

Related

How to by pass HTML encoding string in text fields?

I am setting a field in my HTML label from Viewbag which has a "'" in the text. when the HTML pulls up it shows ' in place of "'". How do I stop it from getting encoded?
Please find the code below.
setting text fileds in the HTML view.
$('#thStudentName').text('#ViewBag.Name');
if (sessionData.data.EventDate2Def != '' || sessionData.data.EventDate2Def != null)
$('#tdWhen').text(sessionData.data.EventDate1Def + ' and ' + sessionData.data.EventDate2Def);
else
$('#tdWhen').text(sessionData.data.EventDate1Def);
$('#tdWhere').text(sessionData.data.FacilityName);
$('#tdLocated').text(sessionData.data.Address1 + ', ' + sessionData.data.City + ', ' + sessionData.data.State + ' ' + sessionData.data.Zip);
$('#tdPhone').text(sessionData.data.Phone);
$('#tdDirections').text(sessionData.data.Directions);
$('#tdRoom').text(sessionData.data.RoomNumber);
Populating a different section with Dynamic data.
function populateSessionTable() {
var count = 1;
$('#SessionTable').html('');
var tableContent = '';
var record = '';
var Sessions = sessionData.data.Sessions;
tableContent = generateTableContent(count, Sessions[0].StartDateTimeDef);
tableContent += '</tbody></table></div>';
$('#SessionTable').html(tableContent);
var radioStatus = '';
for (var i = 0; i < Sessions.length; i++) {
var content = Sessions[i];
radioStatus = '';
if (content.Capacity == content.Registered || content.Closed)
radioStatus = '<input disabled class="selected-session radio" name="SessionId" type="radio" value="' + content.SessionId + '">';
else if (content.StartDateTimeDef == '#ViewBag.WorkshopDateDef' && t24to12Convert(content.StartTimeString) == t24to12Convert('#ViewBag.WorkshopTime'))
radioStatus = '<input class="selected-session radio" checked name="SessionId" type="radio" value="' + content.SessionId + '">';
else
radioStatus = '<input class="selected-session radio" name="SessionId" type="radio" value="' + content.SessionId + '">';
record += '<tr>';
record += '<td class="session-schedule-table-btn">';
record += radioStatus;
record += '</td>';
record += '<td class="session-schedule-table-session-number"> ' + content.Number + ' </td>';
record += '<td class="session-schedule-table-session-start-time">' + t24to12Convert(content.StartTimeString) + '</td>';
record += '</tr>';
$('#SessionTBody' + count).append(record);
record = '';
if(Sessions.length != i + 1)
{
if(Sessions[i].StartDateTimeDef != Sessions[i + 1].StartDateTimeDef)
{
tableContent = '';
count++;
tableContent = generateTableContent(count, Sessions[i+1].StartDateTimeDef);
tableContent += '</tbody></table></div>';
$('#SessionTable').append(tableContent);
}
}
}
}
populateSessionTable();
The preview shows the name in the correct format, but when it gets rendered instead of having the quote, it shows '
This is how the output is coming up
So finally it was a stupid problem and I swear I had tried this before, but this is the code that worked.
var stuName = '#ViewBag.Name';
stuName = stuName.replace("'", "'");
$('#thStudentName').text(stuName);

how to change select box value based on saved select box value

if (itemPrice != null) {
var option = null;
for (var i = 0; i < itemPrice.d.length; i++) {
option += '<option value=' + itemPrice.d[i].ListNum + '>' + itemPrice.d[i].ListName + '</option>';
}
} else {
SessioExp(response.statusText);
}
tblRow += '<td style="width:20%"><div id="' + d.ItemCode + '"><select class="customSelect" name="dropdown" >' + option + '</select></div></td>';
$.each(itemLinked, function (k, v) {
if (d.ItemCode == v.ITEMCODE) {
//Here set v.PRICELIST TO OPTION VALUE
if (v.ISLINKED) {
tblRow += '<td style="width:10%" align="center"><span id="existingData" class="fa fa-times" aria-hidden="false" style="display: none;"></span></td>';
tblRow += '<td style="width:10%" align="center"><input type="checkbox" class="chkLinked" checked /></td>';
flage = false;
}
}
});
I want set select box value when condition true if (d.ItemCode == v.ITEMCODE)
tblRow += '<td style="width:20%"><div id="' + d.ItemCode + '"><select class="customSelect" name="dropdown" >' + option + '</select></div></td>';
Here we want to show first saved value.
Assuming that your generated options have been appended to the html, you can simply call the JS function optionID.selected = true
So for that you will need to define ids to all your options
// assuming that all your values are unique
for (var i = 0; i < itemPrice.d.length; i++) {
option += '<option id=' + itemPrice.d[i].ListNum + ' value=' + itemPrice.d[i].ListNum + '>' + itemPrice.d[i].ListName + '</option>';
}
//pass the option id here
//P.S you can only call this funtion only if the options have been appended to the html
function defineOption(optionID) {
document.getElementById(optionID).selected = true;
}

How to recreate a table dynamically in javascript

I am creating a table dynamically in a return statement from ajax. But I see only one row of the table, although debugger shows data.length as 4. How do I correct the recreating of table?
// using ajax return to recreate a table
// ...
if (data.length > 0) {
for (var i = 0; i < data.length; i++) {
var $mytablerow = $(
'<table>' +
'<tbody>' +
'<tr>' +
'<td id="td' + data[i].Value + '" >' +
data[i].Text +
'</td>' +
'</tr>' +
'</tbody>' +
'</table>'
);
}
}
var $mylst = $("#Userslist");
$mylst.html($mytablerow);
// ....
using ajax return to recreate a table
...
if (data.length > 0)
{
var $mytablerow = '<table><tbody>';
for (var i = 0; i < data.length; i++)
{
$mytablerow += $(
'<tr>' +
'<td id="td' + data[i].Value + '" >' + data[i].Text + '</td>' +
'</tr>');
}
$mytablerow += '</tbody></table>';
}
var $mylst = $("#Userslist");
$mylst.html($mytablerow);
....
I think you should use a variable outside the loop. For example:
if(data.length > 0) {
var $myTable = '<table><tbody>';
for (var i = 0; i < data.length; i++) {
$myTable += '<tr><td id="td' + data[i].Value + '" >' + data[i].Text + '</td></tr>';
}
$myTable += '</tbody></table>';
}
var $mylst = $("#Userslist");
$mylst.html($myTable);
You have problem in your script. To fix this problem replace by this script:
if (data.length > 0)
{
var $mytablerows = '<table>' + '<tbody>';
for (var i = 0; i < data.length; i++) {
$mytablerows += '<tr>' +
'<td id="td' + data[i].Value + '" >' + data[i].Text + '</td>' +
'</tr>';
}
$mytablerows += '</tbody>' + '</table>';
var $mylst = $("#Userslist");
$mylst.html($mytablerows);
}
That looks like you are creating a single row table each iteration and then only adding the last table you create. You need to create the table stuff once and then iterate to create the rows.

Fill table in javascript with data from db

I have an html <table> that I need to fill with data from a database query. The query returns 10 rows and then sends the data to the method fill(data) to fill the table:
function getTopQ() {
alert("Get top Qs");
callServer('fill', 'checkConnection', false, 'SelectTopQues.php');
}
function fill(data) {
alert("ready to fill now");
$('#table').html('');
var search = '#table';
for (var i = 0; i < data.length; i++) {
$('#table').listview("refresh");
var Questions = data[i];
var str = '<td " ID="' + Questions[0] +
'" Question="' + Questions[1] +
'" UserID="' + Questions[2] +
'"CategoryId"' + '" SubCategoryId"' + '" DatePosted"' + '"';
str += '">'; //end li
str += '<a href="" data-transition="fade">';
str += Questions[1];
str += '</a>';
//str += '<span class="hiddenData">' + item[13] + '</span>';
str += '</td>';
$('#table').append(str);
$('#table').listview("refresh");
}
console.log(data);
console.log($('#table'));
$('#table').listview("refresh");
}

Pass value from loop to javascript function

I have following code:
var storedNames = JSON.parse(localStorage.name);
var mytable = "<table> cellpadding=\"0\" cellspacing=\"0\"><tbody><tr>";
for (var i = 0; i < storedNames.length; i++) {
if (i % 2 == 1 && i != 1) {
mytable += "</tr><tr>";
}
mytable += "<td>" + storedNames[i].name +" "+ storedNames[i].email+"</td><td><img id='arrow' src='arrow.png' height='20' width='20' onclick='redirectToDetail();' ></td></tr>";
}
mytable += "</tbody></table>";
document.write(mytable);
here, in redirectToDetail function i want to i value . How can I pass this?
Any idea?
thank u in advance
try this
mytable += "<td>" + storedNames[i].name +" "+ storedNames[i].email+"</td><td><img id='arrow' src='arrow.png' height='20' width='20' onclick='redirectToDetail(\'"+ i +"\');' ></td></tr>";
and take that in redirectToDetail
function redirectToDetail(val){
alert(val);
}
Just add the value as a literal constant that is passed to the onclick event and you are home free. In addition, I would strongly encourage you to consider using an array and joining the strings as you will yield much better performance particularly in IE.
var storedNames = JSON.parse(localStorage.name);
var mytable = ['<table cellpadding="0" cellspacing="0"><tbody><tr>'];
for (var i = 0; i < storedNames.length; i++) {
if (i % 2 == 1 && i != 1) {
mytable.push("</tr><tr>");
}
mytable.push('<td>' + storedNames[i].name + ' ' + storedNames[i].email + '</td><td><img id="arrow" src="arrow.png" height="20" width="20" onclick="redirectToDetail(' + i + '"></td></tr>"');
}
mytable.push("</tbody></table>");
document.write(mytable.join());
Now you can declare you onclick function like so:
function redirectToDetail(value) {
//do stuff with the value
}
try this
onclick='redirectToDetail(\'"+i+"\')
I think this will do. check it.
mytable += "<td>" + storedNames[i].name +" "+ storedNames[i].email+"</td><td><img id='arrow' src='arrow.png' height='20' width='20' onclick='redirectToDetail(" + i + ");' ></td></tr>";

Categories

Resources