I am trying to select a row in a table I have created and need use the values. The issue I am having is I created it using doms in javascript and got the values from a stored procedure which then populates the table.
so i use a simple div with an id -
<div id="Tab1" class="tab-pane fade in active"></div>
to create the table and populate it i use an ajax call -
function GetcarData() {
$.ajax({
type: "post",
data: JSON.stringify({
price: slidval,
}),
url: "/index.aspx/GetData",
dataType: "json",
contentType: "application/json",
success: function (object) {
responseData(object);
},
complete: function (object) {
},
error: function (object) {
}
});
}
function responseData(object) {
var stringed = JSON.stringify(object.d)
var arr = JSON.parse(stringed);
var i;
var out = "<table id='table' class='table table-striped'>";
var rowHeader = $("<tr></tr>").appendTo(out);
out += "<td><font size='4'>Make</font></td>";
out += "<td><font size='4'>Model</font></td>";
out += "<td><font size='4'>Version</font></td>";
out += "<td><font size='4'>Engine</font></td>";
out += "<td><font size='4'>(AV)Price new</font></td>";
out += "<td><font size='4'>(Av)Price used</font></td>";
out += "<td><font size='4'>Image</font></td>"
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Make +
"</td><td>" +
arr[i].Model +
"</td><td>" +
"£" + arr[i].version +
"</td><td>"+
arr[i].Engine_size +
"</td><td>" +
"£" + arr[i].price_new +
"</td><td>" +
"£" + arr[i].price_used +
"</td><td><img src="+arr[i].image_url+" width='150' height='100'>" +
"</td></tr>";
}
out += "</table>";
document.getElementById("Tab1").innerHTML = out;
}
Now the issue I have is I cant seem to select a row.
I tried
("#table tr").click(function(){
alert("selected");
});
but that did not work.
Anyhelp would be appreciated
You created a set of elements that weren't in the DOM when page and were only added after initial DOMContentLoaded
To listen for events on elements that are dynamically added, removed via JavaScript DOM manipulations, you need to use slightly different event listener.
$(document).on('%eventName%', '%selector%', function() { // do your stuff });
Related
I am creating dynamic table and appending it to Div tag on my .php page. On my .php page, I have dynamic buttons and if I click on any of the dynamic buttons, the dynamic table is rendered which has multiple headers and rows (for which I have written for loops with ajax requests). The issue is that, if i click on any of the dynamic buttons again, the current dynamic table data is appended to the previous dynamic table, instead I want to remove previously appended table data and render the current dynamic table data. I tried to empty the div tag but nothing seems working here. Hope I get some help, thanks in advance. Below are my .php and .js files:
.php file- I didnt post the function definition for get_Btns() as it is the basic php function to fetch data from the database:
<?php
function get_Btns() {
include "config.php";
$btns = $stmtDivision->fetchAll(PDO::FETCH_ASSOC);
foreach($btns as $btn){
echo "<input type='button' id='".$btn['divisionid']."' value='".$btn['division_name']."'
onclick=getData('".$btn['divisionid']."') >" ; echo "<br/>"; ?>
<script src="./user.js"></script>
<?php }
}
?>
<?php include "templates/header.php"; ?>
<div id="buttons_panel" style="text-align:center">
<?php echo get_Btns();?> </div>
<div id="div" class="divClass" ></div> <br/>
.js file:
function getData(value) {
document.getElementById("div");
var tableHtml = $('<table></table>');
var selectedManager = value;
var isEmpty = $('#div').empty();
// document.getElementById("div").innerHTML === "";
// document.getElementById("div").HTML === "";
// var isEmpty = $("#div").html() === "";
//$(".divclass").empty();
var teams = null;
$.ajax({
url: 'data.php',
method: 'post',
data: 'selectedManager=' + selectedManager,
async: false,
success: function(data) {
teams = JSON.parse(data);
}
});
for (var k = 0; k < teams.length; k++) {
const selectedteam = teams[k];
var selectedteamid = team[k].teamid;
var htmlth = "";
var html = "";
htmlth = "<tr>" + "<th id='thgrp' colspan='4' background-color: #013466;>" + teams[k].teamname + "</th>" +
"<th colspan='2' background-color: #62b8b6;>" + "<a href='Update.php?groupid=" + selectedteam.teamid + "' >" +
'Update Team member' + "</a>" + "</th>" + "</tr>" +
"<tr>" + "<th>" + "<img src='images/member.png'>" + "<b>" + "<div>" + 'Member' + "</div" + "</th>" +
"<th>" + "<img src='images/phone.png'>" + "<b>" + "<div >" + 'Phone' + "</div" + "</th>" +
"<th>" + "<img src='images/email.png'>" + "<b>" + "<div >" + 'Email' + "</div" + "</th>" + "</tr>";
tableHtml.append(htmlth);
var members = null;
$.ajax({
url: 'data.php',
method: 'post',
data: 'selectedteamid=' + selectedteamid,
async: false,
success: function(data) {
members = JSON.parse(data);
console.log(members);
}
});
for (var i = 0; i < members.length; i++) {
html += "<tr>" + "<td>" + members[i].name + "</td>" +
"<td>" + members[i].phone + "</td>" + "<td>" + members[i].email + "</td>";
}
tableHtml.append(html)
}
$("#div").append(tableHtml);
value = "";
}
Issue solved, I tried to empty the dynamic table that I have created instead of emptying the div tag on my html page. I did this earlier but I didn't do it properly. Thank you so much everyone for your time
This is the code:
tableHtml.attr('id', 'tableHtmlId');
$('#tableHtmlId').empty();
here, I am using form wizard. Using ajax to load the data and data are append in html.
ajax code :
$.ajax({
url: '<?php echo base_url(); ?>booking/listSiteUrl',
type: 'post',
dataType: 'json',
success: function (response) {
if (response.success == 1) {
var row = '';
var i = 1;
$.each(response.row_data, function (index, value) {
row += "<tr><td>" + i + "</td><td>" + value.url + "</td><td>" + value.p1_name + "</td><td hidden>" + value.id + "</td><td hidden>" + value.f_n + "</td><td><div class='radio-list'><label><input type='radio' id='f_n_val' name='select_val' data-url='" + value.url + "' data-pub='" + value.p1_name + "' data-id='" + value.id + "' data-follow='" + value.f_n + "' required='required'></label></div></td></tr>";
i++;
});
$("#results").html(row);
// $("input[type=radio]").uniform();
} else {
var row = '';
row += "<tr><td colspan='4' class='text-center'>No Records Found</td></tr>";
$("#results").html(row);
}
}
});
How to apply style sheet on a radio button? you can show in image very clearly...
When I am using uniform style i.e. ($("input[type=radio]").uniform();) work fine and radio button style is applied bt problem in when I am checking validation that time it will look like in below image :
Please help me to find out the way to solve this.
You can create your class in css as
.myradio{
// your code here
}
and then
$("input[type=radio]").addClass('myradio');
Let me first say that I've been coding for less than a week. I'm trying to create a javascript that will refresh my data using an AJAX call that will spit out a PHP's JSON encoded file into a more readable file.
I've successfully spit out the json into an HTML table, however, I want to auto refresh this data so when the database changes, so will my HTML.
$(document).ready(function(){
refresh();
});
function refresh() {
setTimeout( function() {
dbupdates();
refresh();
}, 500);
}
function dbupdates(){
$.ajax({
url: 'fetchtest.php',
type: 'get',
dataType: 'JSON',
success: function(response){
// for loop to only write 10
for(var i=0; i<10; i++){
var id01 = response[i].id1;
var id02 = response[i].id2;
var id03 = response[i].id3;
// tr located in html
var tr_str = "<tr>" +
"<td align='center'>" + id01 + "</td>" +
"<td align='center'>" + id02 + "</td>" +
"<td align='center'>" + id03 + "</td>" +
"</tr>";
// table ID in html file
$("#HTMLTABLE").append(tr_str);
}
}
});
};
When I run the web page, it goes into an infinite loop where it just creates new 10 entries table of the same data (probably does change if db changes).
I know exactly why this happens but what function do I need to use to actually refresh only 10 table?
Thanks
No use append() replace into html() function use solved your problems
<div id="HTMLTABLE"></div>
<script>
$(document).ready(function(){
refresh();
});
function refresh() {
setTimeout( function() {
dbupdates();
refresh();
}, 1500);
}
function dbupdates(){
$.ajax({
url: 'fetchtest.php',
type: 'get',
dataType: 'JSON',
success: function(response){
// for loop to only write 10
var tr_str ='';
for(var i=0; i<response.length; i++){
var id01 = response[i].id;
var id02 = response[i].name;
var id03 = response[i].salery;
// tr located in html
tr_str += "<tr>" +
"<td align='center'>" + id01 + "</td>" +
"<td align='center'>" + id02 + "</td>" +
"<td align='center'>" + id03 + "</td>" +
"</tr>";
// table ID in html file
}
$("#HTMLTABLE").html(tr_str);
}
});
};
</script>
I'm trying to get content from a json file, but until now I get nothing.
I have the status connection == 200 and I can see the content in the chrome console
but I get nothing when I try to display the data to html table, but when I use the same jquery code with api from another service like import.io things works fine.
Can you tell me what am I doing wrong?
This api is from kimonolabs.
$(document).ready(function () {
var tabel = '<table><THEAD><caption>Calendário</caption></THEAD>';
tabel += '<th>' + 'Hora' + '</th>' + '<th>' + 'Equipas' + '</th><th>' + 'jornda' +
'</th><th>' + 'Data' + '</th>';
$.ajax({
type: 'GET',
url: 'https://api.myjson.com/bins/1dm6b',
dataType: 'json',
success: function (data) {
console.log(data);
$('#update').empty();
$(data.m_Marcadores).each(function (index, value) {
tabel += '<tr><td>' + this.posicao + '</td>' + '<td>' + this.golos + '</td></tr>';
}); //each
tabel += '</table>';
$("#update").html(tabel);
} //data
}); //ajax
}); //ready
According to JSON structure you should iterate over data.results.m_Marcadores array:
$(data.results.m_Marcadores).each(function (index, value) {
tabel += '<tr><td>' + this.posicao + '</td><td>' + this.golos + '</td></tr>';
});
Another problem. In header of the table you setup 4 colums, but in loop you are creating only two of them. Number of header columns should be the same as other row td.
Also you need to wrap th elements in tr. For example, fixed table header:
var tabel = '<table>' +
'<THEAD><caption>Calendário</caption></THEAD>' +
'<tr>' +
'<th>Hora</th><th>Equipas</th><th>jornda</th><th>Data</th>' +
'</tr>';
Demo: http://jsfiddle.net/onz02e43/
I have a ajax json retrieving all query results in a div.I'm not sure how to introduce pagination though.
<script>
$(document).ready(function () {
var hdnIds = document.getElementById('<%= HiddenField1.ClientID %>').value;
$.ajax({
type: "POST",
url: "WebService1.asmx/GetEmployees",
data: "{userid: " + JSON.stringify(hdnIds) + " }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (list) {
$("#Something").append("<ul id='bullets' class='ul1'></ul>");
for (i = 0; i < list.d.length; i++) {
$("#bullets").append("<li class='li1'>"
+ "<div style='float:left; width:20%'>"
+ "<img id='image' src='Handler3.ashx?id=" + list.d[i].id + "' />"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small; font-style:bold'>" + list.d[i].UserName + "</p>"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small'>" + list.d[i].Created_on + "</p>"
+ "</div>"
+ "<div style='float:left; width:80%'>"
+ "<p class='p11'>" + list.d[i].Statusmes + "</p>"
+ "</div>"
+ "</li>");
}
},
error: function (e) {
$("#Something").html("There was an error retrieving records");
}
});
});
</script>
And html as
<div id="Something"></div>
ANy help will be greatly appreciated!
First, I would read up on javascript templating. There are a lot of libraries out there that will allow you to remove the bloated html code from your JS code so that it's easier to manage. Something like this: https://github.com/BorisMoore/jquery-tmpl.
After that, you should put the responsibility of pagination on the server side and let the JS/Ajax handle the calls to retrieve the data set. For instance:
//server side
var start = request.params.start //retrieve start index for data set
var limit = request.params.limit //retrieve max number of data set size
return db.Model.find({start: start, limit: limit, ...})
//client side JS/Ajax
//load first page 0-9
$.ajax({
url: '/my/data/url',
params: {
start: 0, //start at first record in db
limit: 10 //only return 10 results
}
}).success(function(data) {
//render data set using template
$.template('#my-data-template', data).renderTo('#someDiv');
});
//load second page 10-19
$.ajax({
url: '/my/data/url',
params: {
start: 10, //start at nth record in db
limit: 10 //only return 10 results
}
}).success(function(data) {
//render data set using template
$.template('#my-data-template', data).renderTo('#someDiv');
});
If I understand the question correctly, you already know about append which is what you need, but you need to change all your ids to classes since there will be more than 1 of them. Then, put all of the html you want to append into a string and just append that html.
HTML:
<div id = "parent">
<div class = "Something"></div>
</div>
JAVASCRIPT (replace to the success AJAX call):
var htmlList = "<div class = "Something"><ul class='bullets ul1'>";
for (i = 0; i < list.d.length; i++) {
htmlList += "<li class='li1'>"
+ "<div style='float:left; width:20%'>"
+ "<img id='image' src='Handler3.ashx?id=" + list.d[i].id + "' />"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small; font-style:bold'>" + list.d[i].UserName + "</p>"
+ "<p style='margin-left:2px; position:relative;color:DodgerBlue;font-size:small'>" + list.d[i].Created_on + "</p>"
+ "</div>"
+ "<div style='float:left; width:80%'>"
+ "<p class='p11'>" + list.d[i].Statusmes + "</p>"
+ "</div>"
+ "</li>");
}
htmlList += "</ul></div>";
$("#parent").append(htmlList);