I've seen others do these things to create a dynamic table element or other HTML on a page:
var $myRow = $('#myRowContainer' + IDRow);
var $column = $('<div />', { 'class': 'col', 'css': { 'width': '30%' } }).appendTo($myRow);
$('<div />', { css: { 'text-align': 'left' } }).append($('<span />', { 'html': objDetails[0].message })).appendTo($column);`
I often create html stuff in javascript like:
jQuery.each(mytable, function (i, obj) {
var newrow = ' <tr> ';
newrow += ' <td> ';
newrow += ' <span> ' + obj.ID + '</span>';
newrow += ' </td> ';
newrow += ' <td> ';
newrow += ' <span> ' + obj.PartNumber + ' </span>';
newrow += '</td>';
newrow += ' <td> ';
var name1 = 'txEI_';
var consecutive = obj.IDc;
var idLabelText = name1 + consecutive;
newrow += ' <input id="' + idLabelText + '" class="' + myCssClassToDetect + '" type="text" value="0" /> ';
newrow += ' </td> ';
newrow += ' </tr> ';
$("#tbDesglose").append(newrow);
//make spinner for new field
makeSpinner(idLabelText);
});
What's the difference? Why choose one over another?
When I see var prefixed with $ in javascript, it just usually means the variable is storing some element that is already wrapped in jQuery.
It's just a coding convention some people do.
Related
There is a table contains Tom select input in my modal. And also I made an add button to add Tom select input. So when I click the add button, I clone the that contains tomselect input, but the tom-select input in the cloned tr doesnt work... How can I use tom-select input dynamically?? here's my code..
show modal :
this.show = function(){
var main = this;
var items= main.items;
var modalTitle = "modalTitle";
var modalMsg = ' <div id="modal-id">';
modalMsg += ' <table id = "MyTable" class="table">';
modalMsg += ' <tbody>';
modalMsg += ' <tr>';
modalMsg += ' <th class="col-xs-3"> 25125211 : </th>';
modalMsg += ' <td class="col-xs-9"><label class="col-xs-3"><input type="radio" class="input-val" name="confirm_radio" id="approve" value="100" required>apporve</label>';
modalMsg += ' <label class="col-xs-3"><input name="confirm_radio" id="refer" type="radio" value="900" required>refer</label></td>';
modalMsg += ' </tr>';
modalMsg += ' <tr id = "tomselect-tr">';
modalMsg += ' <th class="col-xs-3"> chooseTomselectOption </th>';
modalMsg += ' <td>';
modalMsg += ' <div class="input-group"><select id="TomSelect_1" placeholder="choose an item..."></select><span class="input-group-btn"><button id="cloneTr" type="button" class="btn btn-tool"><i class="fa fa-plus"></i></button></span></div>';
modalMsg += ' </td>';
modalMsg += ' </tr>';
modalMsg += ' </tbody>';
modalMsg += ' </table>';
modalMsg += ' </div>';
var modalBtn1Text = "done";
var modalBtn2Text = "cancel";
var modalCallback;
var updateCallback = function(){
agreementInfo.saveInfo();
};
modalCallback = updateCallback;
this.modal = new _modal.show(modalTitle
,modalMsg
,modalBtn1Text
,modalBtn2Text
,modalCallback
);
cloneTr function :
function cloneTr(){
trNum++;
var $newTr= $("#tomselect-tr").clone();
$newTr.attr("id", "tomselect-tr""+trNum);
$newTr.find("#TomSelect_1").attr("id","TomSelect_"+trNum);
$("#MyTable").find("tbody").find("#tomselect-tr"").after($addChoiceGrantorTr);
var targetDiv = "TomSelect_"+trNum;
addSelector(targetDiv);
}
addSelector function
function addSelector(_targetDiv){
var selector = new TomSelect("#"+_targetDiv,{
valueField: 'USR_NO',
searchField: ['USR_NM', 'USR_ID', 'USR_EMAIL', 'GP_NM'],
maxItems: 1,
maxOptions: 100,
options: items,
render: {
option: function(data, escape) {
console.log(escape);
return '<div>' +
' <span class="USR_NM">' + escape(data.USR_NM) + '</span>' +
' <span class="GP_NM">' + escape(data.GP_NM) + '</span>' +
' <span class="USR_ID">' + escape(data.USR_ID) + '</span>' +
' <span class="USR_EMAIL">' + escape(data.USR_EMAIL) + '</span>' +
'</div>';
},
item: function(data, escape) {
return '<div id="'+itemDivTxt+'" title="' + escape(data.USR_NO) + '" data-name="' + escape(data.USR_NM) + '">' +
' <span class="tom-select-name">' + escape(data.USR_NM) + '</span>' +
' <span class="tom-select-group">' + escape(data.GP_NM) + '</span>' +
'</div>';
}
}
});
selector.clearCache();
}
How can I use tomselect dynamically or initialize when I click the add button?? thanks
I tried to clone the wrong object... I made a temporary tr object and clone it... and It works
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);
I'm trying to insert a button in the end of each row of the table receitas but the buttons are being set at the start of the table instead of the end of each row.
function mostraTabelaTeste(aTipo, aLista) {
tb = '<table>';
tb += '<tr><th>Tipo</th><th>Nome</th><th>Tempo</th><th>Custo</th><th>Dificuldade</th></tr>';
for(let i in receitas) {
if(receitas[i].tipo==aTipo) {
tb += '<tr><td>' + receitas[i].tipo + '</td><td>' + receitas[i].nome + '</td><td> '+ receitas[i].tempo + '</td><td>' + receitas[i].custo + '</td><td>' + receitas[i].dificuldade + '</td></td><input type="button" id="remove_' + i + '" value="x"</td></tr>';
}
}
tb += '<table>';
document.getElementById(aLista).innerHTML = tb;
}
The line where I put all the properties into the table row (inside of for), I have an input which should be set at the end of the row but instead, it is going to the top of the table.
It's just a type error in the cell wrapping the button you're creating </td> instead of starting <td>
see belown snippet :
receitas = [
{tipo:"typ1",nome:"nome1",tempo:"tempo1",custo:"custo1",dificuldade:"dificuldade1"},
{tipo:"typ2",nome:"nome2",tempo:"tempo2",custo:"custo2",dificuldade:"dificuldade2"},
{tipo:"typ1",nome:"nome3",tempo:"tempo3",custo:"custo3",dificuldade:"dificuldade3"},
{tipo:"typ1",nome:"nome4",tempo:"tempo4",custo:"custo4",dificuldade:"dificuldade4"},
]
function mostraTabelaTeste(aTipo, aLista) {
tb = '<table>';
tb += '<tr><th>Tipo</th><th>Nome</th><th>Tempo</th><th>Custo</th><th>Dificuldade</th></tr>';
for (let i in receitas) {
if (receitas[i].tipo == aTipo) {
tb += '<tr><td>' + receitas[i].tipo + '</td><td>' + receitas[i].nome + '</td><td> ' + receitas[i].tempo + '</td><td>' + receitas[i].custo + '</td><td>' + receitas[i].dificuldade + '</td><td><input type="button" id="remove_' + i + '" value="x"</td></tr>';
}
}
tb += '<table>';
document.getElementById(aLista).innerHTML = tb;
}
mostraTabelaTeste("typ1","table");
<div id="table"></div>
You may need to add one more th for button column in first row. Like below:
tb += '<tr><th>Tipo</th><th>Nome</th><th>Tempo</th><th>Custo</th><th>Dificuldade</th><th> </th></tr>';
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");
}
this is my view
im trying to access row index using this method
$("input.deliverQty").focusout(function (e) {
var table = document.getElementById('invoiceDetailTbl');
var DeliverQty = $(this).val();
var rowId = $(this).closest('tr').attr('rowIndex');
//var OrderQty = $(this).closest('tr').find('input.payingAmt').val();
var OrderQty = table.rows[parseInt(rowId) + 1].cells[2].childNodes[0].data;
but result was undefined
i'm append my table like this
for (var i = 0; i < data[0].itemDetails.length; i++) {
itmCode = data[0].itemDetails[i].item_Code;
itmName = data[0].itemDetails[i].item_Name;
OQty = parseInt(data[0].itemDetails[i].item_Qty);
//netAmt = parseFloat(data[i].Net_Amt).toFixed(2);
//paidAmt = parseFloat(data[i].Paid_Amt).toFixed(2);
//balance = (parseFloat(netAmt) - parseFloat(paidAmt)).toFixed(2); //id = "damt['+i+']"
$("#invoiceDetailTbl tbody").append("<tr id=" + i + ">" + "<td>" + itmCode + "</td>" + "<td>" + itmName + "</td>" + "<td>" + OQty + "</td>" + "<td>" + '<input type="text" class="deliverQty form-control input-sm" style="width: 100px;" placeholder="Deliver Qty" id="dqty">' + "</td>" + "<td>" + '<span class="glyphicon glyphicon-trash"></span>' + "</td>" + "</tr>");
//noOfItems = parseInt(noOfItems) + parseInt(OQty);
//noOfProducts = parseInt(noOfProducts) + 1;
}
rowIndex is not an attribute, so try .prop()
var log = (function() {
var $log = $('#log');
return function(msg) {
$('<p/>', {
text: msg
}).appendTo($log)
}
})();
jQuery(function() {
$('tr input').each(function() {
var rowId = $(this).closest('tr').attr('rowIndex');
log('attr: ' + rowId);
rowId = $(this).closest('tr').prop('rowIndex');
log('prop: ' + rowId);
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input />
</td>
</tr>
<tr>
<td>
<input />
</td>
</tr>
</table>
<div id="log"></div>