Make dropdown item selected true dynamically - javascript

I am making dropdown item selected true dynamically using below lines of code
for(var i in data) {
var book_id = data[i]['book_id'];
var indivudvalbookdetails = data[i]['indivudvalbookdetails'];
var id=1;
for(var j in indivudvalbookdetails) {
if(indivudvalbookdetails[j]['status'] == undefined || indivudvalbookdetails[j]['status'] == "")
{
$('.library_info_tbl tbody').append('<tr>' +
'<td class="text-center centeralign"> ' + data[i]['subject'] + '</td>' +
'<td class="text-center centeralign"> ' + data[i]['title'] + ' </td>' +
'<td class="text-center centeralign"> ' + data[i]['isbn'] + '</td>' +
'<td class="text-center centeralign"> ' + data[i]['author'] + ' </td>' +
'<td class="text-center centeralign"> ' + indivudvalbookdetails[j]['acquisitionno'] + '</td>' +
'<td class="text-center centeralign"><div class="btn-group">' +
'<input type="text" class="hide" id="acquisitionno' + id + '" value="' + indivudvalbookdetails[j]['acquisitionno'] + '" class="form-control">' +
'<select id="status' + id + '" class="form-control">' +
'<option value="Select">Select</option>'+
'<option value="Damaged"' +
indivudvalbookdetails[j]['status'] == "Damaged" ? 'selected="true"': 'selected="false">Damaged</option>'+
'<option value="Lost"' +
indivudvalbookdetails[j]['status'] == "Lost" ? 'selected="true"' : ' selected="false">Lost</option>' +
'</select>'+
//'<input type="text" id="status' + id + '" class="form-control">' +
'</div></td>' +
'</tr>');
id++;
}
}
It is displaying the code in html like:
"selected="false">Lost selected="false">Lost
selected="false">Lost selected="false">Lost selected="false">Lost"

The string termination is not right and the if condition as well.
Check the code below:
var id = 'select';
var indivudvalbookdetails = [{
status: 'Damaged'
}]
var j = 0;
var select = '<select id="status' + id + '" class="form-control">' +
'<option value="Select">Select</option>' +
'<option value="Damaged"' +
(indivudvalbookdetails[j]['status'] == "Damaged" ? 'selected="selected"' : '') + '>Damaged</option>' +
'<option value="Lost"' +
(indivudvalbookdetails[j]['status'] == "Lost" ? 'selected="selected"' : '') + '>Lost</option>' +
'</select>'
document.getElementById('main').innerHTML = select;
<div id="main"></div>

Related

Appending data fetched by an AJAX call to an already existing list in UI & saving the data fetched to the already saved list in localstorage

I have a page in which I have to show list of data in UI through ajax & append the list data in html table save that list data into Local Storage with Jquery, My question is that I want to implement lazy load in UI such that user clicks a button (Click to view more list), and after clicking the button the ajax calls another list with limit & offset to show more list & append the new list below the existing list in UI and also save the data into local storage along with the existing data present.
My Ajax Call for List Data
var sendingData = {
limit: "50000",
offset: "0"
};
$.ajax({
type: 'POST',
url: "/Common/Item/getselleritems?SellerId=" + userid,
data: sendingData ,
crossDomain: true,
success: function (data)
{
localStorage.setItem("productCode", JSON.stringify(data));
},
error()
{
//Do something
}
});
``
My Html design Function
function showProducts()
{
var productsStorage = localStorage.getItem("productCode");
var products = JSON.parse(productsStorage);
var trHTML = '';
$("table tbody").html("");
$.each(products.Data, function (key, value)
{
trHTML += '<tr>'
+ '<td class="d-md-flex align-items-center">' + '<figure style="' + imgStyle + '"><a href="" title="Photo title" data-effect="mfp-zoom-in">' +
'<img src="' + imgSrc + '" alt="thumb" class="lazy"></a></figure>' +
'<div class="flex-md-column">' +
'<h4 class="package_name" id="itemdescription_' + value.Id + '" onclick = "packageDetails(\'' + value.Price + '\',\'' + value.Name + '\',\'' + value.Description
+ '\',\'' + itemTimeSlotType + '\',\'' + value.ServiceName + '\',\'' + value.PreparationTime + '\',\'' + value.Quantity + '\')" >' +
'<i class="icon_box-selected" style="' + style + '; margin-right:3px"></i>' +
value.Name + '</h4>' +
'<p>' + value.Description + '</p>' +
'<em>' + "Available In: " + itemTimeSlotType + '</em>' + '<br>' +
'<span class="stars_sellerItem" style="' + starStyle + '">' + value.FoodtestAvgRating + ' <i class="icon_star"> </i> ' +
'</span>' +
'</div>' +
'</td>' + '<td style="padding: 0.75rem 0 0.75rem 0;">' +
'<strong id="itemprice_' + value.Id + '">' +
'<i class="fa fa-inr" aria-hidden="true"></i>' + value.Price +
'</strong>' +
'</td>' +
'<td class="options">' +
'<div class="dropdown dropdown-options">' +
'<i class="icon_plus_alt2"></i>' +
'<div class="numbers-row number" id="item2_' + value.Id + '" data-id="' + value.Id + '">' +
'<input type="text" value="1" class="form-control" name="quantity" id="itemvalue_' + value.Id + '" onchange="getval(' + itemId + ');" readonly>' +
'<div class="inc button_inc plus">' + '+' + '</div><div class="dec button_inc minus">' + '-' + '</div>' + '</div>' +
'</td>' + '</tr>';
}
$("table tbody").append(trHTML);
}

how to append value in td

I am getting dynamic values in table using Datatables. I am getting my desired value in alert, but I want to show that value in table. for that purpose I used .append, .html but no luck. How can I show = my value in <td>. I also try to gave gave td an id e.g <td id="files">
here is my code:
function format(d) {
var str = d.files;
var myarr = str.split(",");
for (var i = 0; i < myarr.length; i++) {
alert(myarr[i]);
$("#files").append("<a href='/uploads/" + myarr[i] + "'>" + myarr[i] + "</a>");
}
// `d` is the original data object for the row
return '<table id="ChildRows" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Contact Person:</td>' +
'<td>' + d.person + '</td>' +
'</tr>' +
'<tr>' +
'<td>Phone:</td>' +
'<td>' + d.phone + '</td>' +
'</tr>' +
'<tr>' +
'<td>Web:</td>' +
'<td>' + d.web + '</td>' +
'</tr>' +
'<tr>' +
'<td>Trade Type:</td>' +
'<td>' + d.ttype + '</td>' +
'</tr>' +
'<tr>' +
'<td>Files:</td>' + '<td id="files">'
'</td>' +
'</tr>' +
'</table>';
}
I hope it will be a easy fix.any help will be highly appreciable
Your issue is that the #files element doesn't exist at the point you attempt to select it. You need to first add that HTML string to the DOM, then append to it.
Alternatively, you could amend the logic which creates that HTML string to include the output of your for loop, like this:
function format(d) {
var str = d.files;
var filesHtml = str.split(",").map(function(file) {
return '' + file + '';
});
return '<table id="ChildRows" cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
'<tr>' +
'<td>Contact Person:</td>' +
'<td>' + d.person + '</td>' +
'</tr><tr>' +
'<td>Phone:</td>' +
'<td>' + d.phone + '</td>' +
'</tr><tr>' +
'<td>Web:</td>' +
'<td>' + d.web + '</td>' +
'</tr><tr>' +
'<td>Trade Type:</td>' +
'<td>' + d.ttype + '</td>' +
'</tr><tr>' +
'<td>Files:</td>' +
'<td id="files">' + filesHtml + '</td>' +
'</tr>' +
'</table>';
}
var html = format({
person: 'John Smith',
phone: '1234 567890',
web: 'http://google.com',
ttype: 'Foobar',
files: 'a.jpg,b.jpg'
});
$('div').append(html);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

in directive, ng-click fires multiple times angularjs

I am creating a directive, which is used to add and remove elements dynamically. But my ng-click fires multiple times while adding and removing elements. Please give suggestions.
Here enable values means to select when 1=>textbox; 2=>selectbutton;3=>Radio button; 4=>CheckBox;5=>+/-
HTML:
<body ng-app = "mainApp" ng-controller = "loginController">
<div id="sampleeid">
<incrementrowsdirective idvalue="sto"
arrayvalues='[]'
labelvalues='["Concepto","Monto","Add/Remove"]'
enablevalues='[2,1,5]'></incrementrowsdirective>
<button ng-click="SampleButton()">Sample
Button</button>
</div>
CODE:
gasapp.directive("incrementrowsdirective", function ($compile) {
var trheaderelements;
var tablenm;
var tablenm1;
var trelements;
var trfirstelement;
var firstelement;
return {
restrict: 'AE',
scope: {
idvalue: '#'
},
template: function (elem, attr) {
return '<div class="col-md-8 col-sm-11 col-xs-11"><table id="tableheaderid"></table> <table id="tableid' + attr.idvalue + '" class="table table-condensed table-striped table-bordered table-hover no-margin">' +
'</table></div>'
},
link: function (scope, iElement, iAttrs) {
scope.labelval = JSON.parse(iAttrs.labelvalues);
scope.enableval = JSON.parse(iAttrs.enablevalues);
scope.arrt = JSON.parse(iAttrs.arrayvalues);
scope.c = 0;
scope.count = 1;
trheaderelements = '<thead><tr id="mytrheader' + scope.idvalue + '" >';
angular.forEach(scope.labelval, function (value, key) {
trheaderelements = trheaderelements + '<th style="width: 20%;"> ' + value + ' </th>';
});
trheaderelements = trheaderelements + "</tr></thead>";
tablenm = angular.element(document.getElementById('tableid' + scope.idvalue)).append(trheaderelements);
$compile(tablenm)(scope);
trfirstelement = "<tr id='mytrfirstelement'>";
angular.forEach(scope.enableval, function (value, key) {
if (value == 1) {
trfirstelement = trfirstelement + '<td><input type="text" name="text1name' + scope.idvalue + value + key + '" ng-model="text1value' + scope.idvalue + value + key + '" id="text1valueeid' + scope.idvalue + value + key + '" > </td>';
}
if (value == 2) {
trfirstelement = trfirstelement + '<td><select id="selectid1value' + scope.idvalue + value + key + '" name="selectname1val' + scope.idvalue + value + key + '" ng-model="selectmodel1val' + scope.idvalue + value + key + '" style="width:185px;"><option>..select..</option><option>Brother</option><option>Sister</option><option>Wife/Husband</option></select></td>';
}
if (value == 3) {
trfirstelement = trfirstelement + '<td><input type="radio" id="radio1idvalue' + scope.idvalue + value + key + '" name="radio1nameval' + scope.idvalue + value + key + '" ng-model="radio1modelval' + scope.idvalue + value + key + '" > </td>';
}
if (value == 4) {
trfirstelement = trfirstelement + '<td><input type="checkbox" id="checkbox1idval' + scope.idvalue + value + key + '" name="checkbox1nameval' + scope.idvalue + value + key + '" ng-model="checkbox1modelval' + scope.idvalue + value + key + '"> </td>';
}
if (value == 5) {
trfirstelement = trfirstelement + '<td> <input type="button" value="+" id="addbtn' + scope.idvalue + value + key + '" ng-click="addRow1(' + scope.c + ')">' +
' </td>';
}
});
trfirstelement = trfirstelement + "</tr>";
firstelement = angular.element(document.getElementById('tableid' + scope.idvalue)).append(trfirstelement);
$compile(firstelement)(scope);
trfirstelement = '';
scope.addRow1 = function (a) {
scope.c++;
scope.count++;
trelements = '<tr id=mytr' + scope.idvalue + scope.c + '>';
angular.forEach(scope.enableval, function (value, key) {
scope.keyvalue = key;
if (value == 1) {
trelements = trelements + '<td><input type="text" name="text1name' + scope.idvalue + scope.c + value + key + '" ng-model="text1value' + scope.idvalue + scope.c + value + key + '" id="text1valueeid' + scope.idvalue + scope.c + value + key + '" > </td>';
}
if (value == 2) {
trelements = trelements + '<td><select id="selectid' + scope.idvalue + scope.c + value + key + '" name="selectname' + scope.idvalue + scope.c + value + key + '" ng-model="selectmodel' + scope.idvalue + scope.c + value + key + '" style="width:100%;"><option>..select..</option><option>Brother</option><option>Sister</option><option>Wife/Husband</option></select></td>';
}
if (value == 3) {
trelements = trelements + '<td><input type="radio" id="radioid' + scope.idvalue + scope.c + value + key + '" ></input> </td>';
}
if (value == 4) {
trelements = trelements + '<td><input type="checkbox" id="checkboxid' + scope.idvalue + scope.c + value + key + '" name="aaa" ></input> </td>';
}
if (value == 5) {
trelements = trelements + '<td> <input type="button" value="+" id="addbtn' + scope.idvalue + scope.c + value + key + '" ng-click="addRow1(' + scope.c + ')">' + ' <input type="button" value="-" ng-click="removerowbutton1(' + scope.c + ')" > </td>';
}
});
trelements = trelements + "</tr>";
tablenm1 = angular.element(document.getElementById('tableid' + scope.idvalue)).append(trelements);
$compile(tablenm1)(scope);
trelements = '';
}
scope.removerowbutton1 = function (index) {
//scope.c--;
alert("Removed")
var myEl = angular.element(document.querySelector('#mytr' + scope.idvalue + index));
myEl.remove();
}
}
};
});
Need to remove the lines,
$compile( firstelement )( scope );
$compile( tablenm1 )( scope );
and replace the line with
firstelement = angular.element(document.getElementById('tableid'+scope.idvalue)).append($compile(trfirstelement)(scope));

jQuery creating tables, but currently keeps repeating the table under the previous one when submit button is clicked

my jQuery creates tables, but currently it keeps repeating the new tables under the previous ones when 'submit' button is clicked. How do I toggle it so it clears the previous table before showing the new table?
Any help would be great thanks!
<script type="text/javascript">
function call_everybody(){
display_results_table();
display_cyclist_results_table();
display_cyclist2_results_table();
}
function display_results_table() {
$("medal_table").empty();
$('<table id = "results_table">').appendTo('#medal_table');
$.get("sam2.php", { Country_1: $('#Country_1').val(), Country_2: $('#Country_2').val(), queryType: $('#differentOptions').val() },
function (results_obtained) {
$('<tr><td>Rank</td>' +
'<td>Country Name</td>' +
'<td>Population</td>' +
'<td>GDP</td>' +
'<td>Gold</td>' +
'<td>Silver</td>' +
'<td>Bronze</td>' +
'<td>Total</td></tr>').appendTo('#results_table');
for (var i = 0; i <= results_obtained.length; i++) {
$('<tr><td>' + (i+1) + '</td>' +
'<td>' + results_obtained[i].country_name + '</td>' +
'<td>' + results_obtained[i].population + '</td>' +
'<td>' + results_obtained[i].gdp + '</td>' +
'<td>' + results_obtained[i].gold + '</td>' +
'<td>' + results_obtained[i].silver + '</td>' +
'<td>' + results_obtained[i].bronze + '</td>' +
'<td>' + results_obtained[i].total + '</td></tr>').appendTo('#results_table');
}
},'json');
$('</table>').appendTo('#medal_table');
}
function display_cyclist_results_table() {
$("cyclist_table").empty();
$('<table id = "cyclist_results_table">').appendTo('#cyclist_table');
$.get("sam3.php", { Country_1: $('#Country_1').val(), Country_2: $('#Country_2').val(), queryType: $('#differentOptions').val() },
function (cyclist_results_obtained) {
$('<tr><td>Country id</td>' +
'<td>Name</td>' +
'<td>Gender</td>' +
'<td>Sport</td></tr>').appendTo('#cyclist_results_table');
for (var j = 0; j <= cyclist_results_obtained.length; j++) {
$('<tr><td>' + cyclist_results_obtained[j].iso_id + '</td>' +
'<td>' + cyclist_results_obtained[j].name + '</td>' +
'<td>' + cyclist_results_obtained[j].gender + '</td>' +
'<td>' + cyclist_results_obtained[j].sport + '</td></tr>').appendTo('#cyclist_results_table');
}
},'json');
$('</table>').appendTo('#cyclist_table');
}
function display_cyclist2_results_table() {
$("cyclist2_table").empty();
$('<table id = "cyclist2_results_table">').appendTo('#cyclist2_table');
$.get("sam4.php", { Country_1: $('#Country_1').val(), Country_2: $('#Country_2').val(), queryType: $('#differentOptions').val() },
function (cyclist2_results_obtained) {
$('<tr><td>Country id</td>' +
'<td>Name</td>' +
'<td>Gender</td>' +
'<td>Sport</td></tr>').appendTo('#cyclist2_results_table');
for (var j = 0; j <= cyclist2_results_obtained.length; j++) {
$('<tr><td>' + cyclist2_results_obtained[j].iso_id + '</td>' +
'<td>' + cyclist2_results_obtained[j].name + '</td>' +
'<td>' + cyclist2_results_obtained[j].gender + '</td>' +
'<td>' + cyclist2_results_obtained[j].sport + '</td></tr>').appendTo('#cyclist2_results_table');
}
},'json');
$('</table>').appendTo('#cyclist2_table');
}
</script>
<title>sam.php</title>
</head>
<body>
<form name="form">
<table>
<tr><td><input name="Country_1" id="Country_1" value="GBR" type="text"></td></tr>
<tr><td><input name="Country_2" id="Country_2" value="USA" type="text"></td></tr>
<td><input id='toggle' type="button" value="Cyclist Comparison" onclick="call_everybody()"/></td></tr>
</table>
</form>
<div id = "toggle_table">
<div id="medal_table"></div>
<div id="cyclist_table"></div>
<div id="cyclist2_table"></div>
</div>
</body>
You need to add -
$('#results_table').remove();
Prior to -
$('<table id = "results_table">').appendTo('#medal_table');

jquery append does not append large html comming from a for loop

It´s is not very clear to me why I am not get any data appended when I have a lot of data to be appended.
When I have 3 objects It works fine, for a larger number it does not append data.
I believe that append is been called before the for loop is finished. Could be that?
building the <tr>'s:
for (var i = 0; i < obj.length; i++) {
if (obj[i].indiceId === 4 && dinamicDom !== 'dinamic_index_busca_edit') {
var dateChkBox = '<p class="pDtPeriodoChk"><input type="checkbox" name="dtPeriodoChk" class="dtPeriodoChk" id="' + i + '_chk">Por Período</p>';
trs = trs + '<tr class="' + dinamicDom + '" style="padding-top:10px;"><td class="smallMediumField ' + i + '" style="padding-top:10px;"><fieldset class="dataFieldset"><legend>' + obj[i].indiceName + '</legend>' + dateChkBox + '<span id="' + i + '_lblDtInicio" class="lblDataInicio" style="display:none"><br />Data Inicio:</span><table><tr><td><img src="/Images/equal.png" alt="Igual a"/></td><td><input type="text" id="' + i + '" name="data" class="selectInput limpar" ';
if (obj[i].valor !== null && obj[i].valor !== '') {
trs = trs + ' value="' + obj[i].valor + '" ';
}
trs = trs + '></td></tr></table><input type="hidden" id="' + obj[i].indiciId + '" name="data_indices" value="' + obj[i].indiciId + '" class="selectInput"></fieldset></td></tr>';
} else {
trs = trs + '<tr class="' + dinamicDom + '"><td class="smallMediumField ' + i + '" style="padding-top:10px;">' + obj[i].indiceName + '<br /><input type="text" id="' + i + '" name="groupBusca" class="selectInput limpar" ';
if (obj[i].valor !== null && obj[i].valor !== '') {
trs = trs + ' value="' + obj[i].valor + '" ';
}
trs = trs + '></td></tr></table><input type="hidden" id="' + obj[i].indiciId + '" name="indicesBusca" value="' + obj[i].indiciId + '" class="selectInput"></td></tr>';
}
}
appending:
$('#tblBusca').append(trs);
Try appending row by row
for (var i = 0; i < obj.length; i++) {
var trs;
if (obj[i].indiceId === 4 && dinamicDom !== 'dinamic_index_busca_edit') {
var dateChkBox = '<p class="pDtPeriodoChk"><input type="checkbox" name="dtPeriodoChk" class="dtPeriodoChk" id="' + i + '_chk">Por Período</p>';
trs = trs + '<tr class="' + dinamicDom + '" style="padding-top:10px;"><td class="smallMediumField ' + i + '" style="padding-top:10px;"><fieldset class="dataFieldset"><legend>' + obj[i].indiceName + '</legend>' + dateChkBox + '<span id="' + i + '_lblDtInicio" class="lblDataInicio" style="display:none"><br />Data Inicio:</span><table><tr><td><img src="/Images/equal.png" alt="Igual a"/></td><td><input type="text" id="' + i + '" name="data" class="selectInput limpar" ';
if (obj[i].valor !== null && obj[i].valor !== '') {
trs = trs + ' value="' + obj[i].valor + '" ';
}
trs = trs + '></td></tr></table><input type="hidden" id="' + obj[i].indiciId + '" name="data_indices" value="' + obj[i].indiciId + '" class="selectInput"></fieldset></td></tr>';
} else {
trs = trs + '<tr class="' + dinamicDom + '"><td class="smallMediumField ' + i + '" style="padding-top:10px;">' + obj[i].indiceName + '<br /><input type="text" id="' + i + '" name="groupBusca" class="selectInput limpar" ';
if (obj[i].valor !== null && obj[i].valor !== '') {
trs = trs + ' value="' + obj[i].valor + '" ';
}
trs = trs + '></td></tr></table><input type="hidden" id="' + obj[i].indiciId + '" name="indicesBusca" value="' + obj[i].indiciId + '" class="selectInput"></td></tr>';
}
$('#tblBusca').append(trs);
}

Categories

Resources