$.ajax({
url: 'https://mailliw88.blogspot.com/feeds/posts/default?start-index=1&max-results=2&alt=json-in-script',
type: 'get',
dataType: "jsonp",
success: function(data) {
var entry = data.feed.entry;
for (var i = 0; i < entry.length; i++) {
postTitle = entry[i].title.$t;
postTitleLink = entry[i].title.$t.replace(/\s+/g, '-').toLowerCase();
items = '<div class="items"><h2>' + postTitle + '</h2></div>';
document.getElementById('showlists').innerHTML += items;
postContent = entry[i].content.$t;
content = '<div class="contentWrap"><div id="close">CLOSE</div><h1>' + postTitle + '</h1><div>' + postContent + '</div></div>';
document.getElementById('showlists').innerHTML += content;
}
}
});
h1 {margin:0}
.contentWrap {border:1px solid red;
padding:5px}
#close {color:red;text-align:right}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='showlists'>
</div>
How to load post content only when clicking the title?
I can use .toggle in jquery but I need to load and "unload" content, not just showing and hiding it. I hope i'm making sense.
My skill is limited to css only, thank you for your help.
You can use display:none to <div class="contentWrap"> and on click of a tag you can show the content using closest() and next().And on click of close again use "display", "none" to hide that content div .
Demo Code :
$.ajax({
url: 'https://mailliw88.blogspot.com/feeds/posts/default?start-index=1&max-results=2&alt=json-in-script',
type: 'get',
dataType: "jsonp",
success: function(data) {
var entry = data.feed.entry;
for (var i = 0; i < entry.length; i++) {
postTitle = entry[i].title.$t;
postTitleLink = entry[i].title.$t.replace(/\s+/g, '-').toLowerCase();
items = '<div class="items"><h2>' + postTitle + '</h2></div>';
document.getElementById('showlists').innerHTML += items;
postContent = entry[i].content.$t;
//added display none and added class = close
content = '<div style="display:none"class="contentWrap"><div class="close">CLOSE</div><h1>' + postTitle + '</h1><div>' + postContent + '</div></div>';
document.getElementById('showlists').innerHTML += content;
}
}
});
//on click of a tag show content
$(document).on("click","a",function(){
//a->closest div->next content->show
$(this).closest(".items").next(".contentWrap").css("display", "block");
})
//onclick of close -> hide again
$(document).on("click",".close",function(){
$(this).closest(".contentWrap").css("display", "none");
})
h1 {margin:0}
.contentWrap {border:1px solid red;
padding:5px}
.close {color:red;text-align:right}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='showlists'>
</div>
Update 1 :
You can assign i value some custom attribute and then use same index value to access post content.In below code snippets i have not send again request to server to load json on click of a instead i have use some variable to store content of data.feed.entry in some variable and then use this to add content .
Demo Code :
var datas = "";
$.ajax({
url: 'https://mailliw88.blogspot.com/feeds/posts/default?start-index=1&max-results=2&alt=json-in-script',
type: 'get',
dataType: "jsonp",
success: function(data) {
//adding entry content in datas to use later
datas = data.feed.entry;
var entry = data.feed.entry;
for (var i = 0; i < entry.length; i++) {
postTitle = entry[i].title.$t;
postTitleLink = entry[i].title.$t.replace(/\s+/g, '-').toLowerCase();
//passing index no i.e : " i " in custom attribute
items = '<div class="items"><h2><a data-val=' + i + ' href="#' + postTitleLink + '">' + postTitle + '</a></h2></div>';
document.getElementById('showlists').innerHTML += items;
}
}
});
$(document).on("click", "a", function() {
$(".contentWrap").remove(); //remove previous div
var ids = $(this).attr('data-val');
console.log(ids)
//getting data that index position got from a tag
postTitle = datas[ids].title.$t;
postTitleLink = datas[ids].title.$t.replace(/\s+/g, '-').toLowerCase();
postContent = datas[ids].content.$t;
content = '<div class="contentWrap"><div class="close">CLOSE</div><h1>' + postTitle + '</h1><div>' + postContent + '</div></div>';
document.getElementById('showlists').innerHTML += content;
})
h1 {margin:0}
.contentWrap {border:1px solid red;
padding:5px}
.close {color:red;text-align:right}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="showlists"></div>
Related
Hi there I'm trying to populate div with data from ajax request, the idea is to use Ajax to get temperature from multiple sensors and for every sensor temperature data I want a separate div column with the data, So on document.ready I use ajax get once to popualte the main page div with the div columns to get the results, but after that I want to use ajax again every 10 seconds to update the data, but how can I do it not generating the containers for the data again? Because of waht I have right now I can't make it to work when I try to make a filter to show/hide the div for specific location.
$(document).ready(function(){
var menu_list = [];
var tr_str = [];
var temp_int= [];
$.ajax({
url: 'getData.php',
type: 'get',
dataType: 'JSON',
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var location = response[i].location;
temp_int[i] = response[i].temp_int;
var temp = response[i].temp;
var hum = response[i].hum;
var dew = response[i].dew;
tr_str[i] = "<div id='locc" + i + "' class='location'>" +
"<span class='title'>" + location + "</span>" +
"<div class='temp" + i + "'><span>Temperatura: </span><span id='check'>" + temp + " °C</span></div>" +
"<div><span>Względna wilgotność: </span><span>" + hum + " %RH</span></div>" +
"<div><span>Punkt rosy: </span><span>" + dew + " °C</span></div>" +
"</div>";
menu_list[i] = "<label for='loc" + i + "'>" +
"<input type='checkbox' id='loc" + i + "' checked='checked'/>" +
"<span class='css-checkbox'></span>" +
"<p>" + location + "</p>" +
"</label>";
}
$("#nav").append(menu_list);
$("#data").html(tr_str);
for(var i=0; i<len; i++){
if (temp_int[i] >= 250) {
$(".temp" + i).css("background-color", "#ff0000");
}
else if (temp_int[i] >= 235) {
$('.temp' + i).css("background-color","#f1c40f");
}
else {
$('.temp' +i).css("background-color","#3498db");
}
}
}
});
$("#loc1").change(function () {
if (this.checked){
$("#locc1").show(!this.checked);
}else {
$("#locc1").hide(!this.checked);
}
});
});
setTimeout(fetchdata,5000);
function fetchdata(){
var tr_str = [];
var temp_int= [];
$.ajax({
url: 'getData.php',
type: 'get',
dataType: 'JSON',
cache: false,
success: function(response){
var len = response.length;
for(var i=0; i<len; i++){
var location = response[i].location;
temp_int[i] = response[i].temp_int;
var temp = response[i].temp;
var hum = response[i].hum;
var dew = response[i].dew;
tr_str[i] = "<div id='locc" + i + "' class='location'>" +
"<span class='title'>" + location + "</span>" +
"<div class='temp" + i + "'><span>Temperatura: </span><span id='check'>" + temp + " °C</span></div>" +
"<div><span>Względna wilgotność: </span><span>" + hum + " %RH</span></div>" +
"<div><span>Punkt rosy: </span><span>" + dew + " °C</span></div>" +
"</div>";
}
$("#data").html(tr_str);
for(var i=0; i<len; i++){
if (temp_int[i] >= 250) {
$(".temp" + i).css("background-color", "#ff0000");
}
else if (temp_int[i] >= 235) {
$('.temp' + i).css("background-color","#f1c40f");
}
else {
$('.temp' +i).css("background-color","#3498db");
}
}
},
complete:function(){
setTimeout(fetchdata,5000);
}
});
}
function openNav() {
document.getElementById("nav").style.width = "350px";
document.getElementById("data").style.marginLeft = "350px";
}
function closeNav() {
document.getElementById("nav").style.width = "0";
document.getElementById("data").style.marginLeft = "0";
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="lib/style.css">
</head>
<body>
<div id="nav" class="menu">
×
<button>Uncheck all</button>
</div>
<div class="nav-wrapper">
<span onclick="openNav()">☰</span>
</div>
<div id="data" class="wrapper"></div>
</body>
</html>
You can see that I use almost the same Ajax request again, is there a way to get teh data at first and generate the divs for the data and then just get the data every 10 seconds and update it only withou generating again the divs?
I'm thinking that what I have right now is making tis unable to work
var $checkboxes = $("#nav :checkbox");
var $button = $("#nav button");
function allChecked(){
return $checkboxes.length === $checkboxes.filter(":checked").length;
}
function updateButtonStatus(){
$button.text(allChecked()? "Uncheck all" : "Check all");
}
function handleButtonClick(){
$checkboxes.prop("checked", allChecked()? false : true)
}
$button.on("click", function() {
handleButtonClick();
updateButtonStatus();
checking();
});
$checkboxes.on("change", function(){
updateButtonStatus();
});
function openNav() {
document.getElementById("nav").style.width = "250px";
}
function closeNav() {
document.getElementById("nav").style.width = "0";
}
function checking() {
var temps = <?php echo json_encode($temps); ?>; //I know this is wrong I would change the loop iteration but it is not working even for one static element when I change it.
$.each( temps, function( index, value ){
$('#loc'+index).change(function () {
if( this.checked ) {
$('#locc'+index).show(!this.checked);
} else {
$('#locc'+index).hide(!this.checked);
}
}).change();
});}
Here is the php file code I'm geting using ajax:
<?php
require 'lib/locations.php';
$search = array('STRING: ', '"');
$search2 = array('INTEGER: ', '"');
$replace = array('','');
$return_arr = array();
for ($i = 0; $i < $c; $i++) {
$temp_int = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.3.1.0");
$temp_int = str_replace($search2,$replace,$temp_int);
$temp = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.1.1.0");
$temp = str_replace($search,$replace,$temp);
$hum = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.1.2.0");
$hum = str_replace($search,$replace,$hum);
$dew = snmpget($ips[$i], $community, ".1.3.6.1.4.1.22626.1.2.1.3.0");
$dew = str_replace($search,$replace,$dew);
$loc = $location[$i];
$return_arr[] = array("location" => $loc,
"temp_int" => $temp_int,
"temp" => $temp,
"hum" => $hum,
"dew" => $dew);
}
echo json_encode($return_arr);
?>
The generated data is an array of one integer and strings
something like this:
var response =[{
"location": "location_1"
"temp_int":250,
"temp":"30.5",
"hum":"49.8",
"dew":"8.5"
},
{"location": "location_1"
"temp_int":250,
"temp":"30.5",
"hum":"49.8",
"dew":"8.5"
}, etc.]
I am trying to append list[i].name and list[i].email once every time sponsorListTree li is being clicked. I can append the document.getElementById("name").appendChild(div_group); but the problem occurs when i click the div a few times, the same data will add up instead of displaying the result only once
$.ajax({
url: 'test.php',
method: 'GET',
success: function(data){
var list = data;
for (i = 0; i < list.length; i++) {
$('#sponsorListTree li').attr('id', function(i) {
return 'sponsorListTree'+(i+1);
});
$('#sponsorListTree').append('<li class="button"><tbody><tr><td><span id="information" class="details"><br/><br/> '+ 'Email: ' + list[i].email + '</br></br> '+ 'Contact No: ' + list[i].contact.phone + ' </br></br> '+ 'Joined date: ' + list[i].date + ' </br> </br>'+ 'InvestedAmount: ' + list[i].account.investedAmount + '</span></td></tr></tbody><table></li>');
}
$("#sponsorListTree li").click(function() {
var name = $(this)[0].innerHTML;
var details = $(this).find('span')[0].innerHTML
var div_name = document.createElement('div');
var div_details = document.createElement('div');
div_name.innerHTML = name;
div_details.innerHTML = details;
div_name.className ="nameDetail";
div_details.className ="detail";
var div_group = document.createElement('div');
div_group.append(div_name);
div_group.append(div_details);
document.getElementById("name").append(div_group);
});
$(".button").click(function() {
$("span").toggleClass("details");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul style=" overflow-x: auto; width: 400%; height: 600px;">
<li>
<a id="root" href="#"></a>
<ul id ="sponsorListTree">
</ul>
</li>
</ul>
<div id = "name" class="control-label"></div>
I have the following markup:
<fieldset>
<legend>Headline Events...</legend>
<div style="width:100%; margin-top:10px;">
<div style="width:100%; float:none;" class="clear-fix">
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Team Filter:
</div>
<div style="width:250px; float:left;">
<input id="teamFilter" style="width: 100%" />
</div>
</div>
<div style="width:400px; float:left; margin-bottom:8px;">
<div style="width:150px; float:left; text-align:right; padding-top:7px;">
Type Filter:
</div>
<div style="width:250px; float:left;">
<input id="typeFilter" style="width: 100%" />
</div>
</div>
</div>
</div>
<div id="diaryTable" name="diaryTable" class="clear-fix">
Getting latest Headlines...
</div>
</fieldset>
I also have the following scripts
<script>
function teamFilterChange(e) {
//alert(this.value());
setCookie('c_team', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
function typeFilterChange(e) {
//alert(this.value());
setCookie('c_type', this.value(), 90);
$c1 = getCookie('c_team');
$c2 = getCookie('c_type');
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param);
}
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
function outputHLDiaryEntries(param) {
var url = "Home/DiaryEntries/";
var data = "id=" + param;
$.post(url, data, function (json) {
var n = json.length;
alert(n + ' ' + json);
if(n == 0){
//json is 0 length this happens when there were no errors and there were no results
$('#diaryTable').replaceWith("<span style='color:#e00;'><strong>Sorry: </strong> There are no headline events found. Check your filters.</span>");
} else {
//json has a length so it may be results or an error message
//if jsom[0].dID is undefined then this mean that json contains the error message from an exception
if (typeof json[0].dID != 'undefined') {
//json[0].dDI has a value so we
//output the json formatted results
var out = "";
var i;
var a = "N" //used to change the class for Normal and Alternate rows
for (i = 0; i < json.length; i++) {
out += '<div class="dOuter' + a + '">';
out += '<div class="dInner">' + json[i].dDate + '</div>';
out += '<div class="dInner">' + json[i].dRef + '</div>';
out += '<div class="dInner">' + json[i].dTeam + '</div>';
out += '<div class="dInner">' + json[i].dCreatedBy + '</div>';
out += '<div class="dType ' + json[i].dType + '">' + json[i].dType + '</div>';
out += '<div class="dServer">' + json[i].dServer + '</div>';
out += '<div class="dComment">' + htmlEncode(json[i].dComment) + '</div></div>';
//toggle for normal - alternate rows
if (a == "N") {
a = "A";
} else {
a = "N";
}
}
//output our formated data to the diaryTable div
$('#diaryTable').replaceWith(out);
} else {
//error so output json string
$('#diaryTable').replaceWith(json);
}
}
}, 'json');
}
$(document).ready(function () {
//Set User Preferences
//First check cookies and if null or empty set to default values
var $c1 = getCookie('c_team');
if ($c1 == "") {
//team cookie does not exists or has expired
setCookie('c_team', 'ALL', 90);
$c1 = "ALL";
}
var $c2 = getCookie('c_type');
if ($c2 == "") {
//type cookie does not exists or has expired
setCookie('c_type', "ALL", 90);
$c2 = "ALL";
}
// create DropDownList from input HTML element
//teamFilter
$("#teamFilter").kendoDropDownList({
dataTextField: "SupportTeamText",
dataValueField: "SupportTeamValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/SupportTeams?i=1",
}
}
}
});
var teamFilter = $("#teamFilter").data("kendoDropDownList");
teamFilter.bind("change", teamFilterChange);
teamFilter.value($c1);
//typeFilter
$("#typeFilter").kendoDropDownList({
dataTextField: "dTypeText",
dataValueField: "dTypeValue",
dataSource: {
transport: {
read: {
dataType: "json",
url: "Home/DiaryTypes?i=1",
}
}
}
});
var typeFilter = $("#typeFilter").data("kendoDropDownList");
typeFilter.bind("change", typeFilterChange);
typeFilter.value($c2);
// Save the reference to the SignalR hub
var dHub = $.connection.DiaryHub;
// Invoke the function to be called back from the server
// when changes are detected
// Create a function that the hub can call back to display new diary HiLights.
dHub.client.addNewDiaryHiLiteToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Start the SignalR client-side listener
$.connection.hub.start().done(function () {
// Do here any initialization work you may need
var param = "true|" + $c1 + "|" + $c2;
outputHLDiaryEntries(param)
});
});
</script>
On initial page load the outputHLDiaryEntries function is called when the signalR hub is started. If I then change any of the dropdownlists this calls the outputHLDiaryEntries but the $('#diaryTable').replaceWith(); does not work. If I refresh the page the correct data is displayed.
UPDATE!
Based on A.Wolff's comments I fixed the issue by wrapping the content I needed with the same element I was replacing... by adding the following line at the beginning of the outputHLDiartEntries function...
var outStart = '<div id="diaryTable" name="diaryTable" class="clear-fix">';
var outEnd = '</div>';
and then changing each of the replaceWith so that they included the wrappers e.g.
$('#diaryTable').replaceWith(outStart + out + outEnd);
replaceWith() replaces element itself, so then on any next call to $('#diaryTable') will return empty matched set.
You best bet is to replace element's content instead, e.g:
$('#diaryTable').html("<span>New content</span>");
I had the same problem with replaceWith() not working when called a second time.
This answer helped me figure out what I was doing wrong.
The change I made was assigning the same id to the new table I was creating.
Then when I would call my update function again, it would create a new table, assign it the same id, grab the previous table by the id, and replace it.
let newTable = document.createElement('table');
newTable.id = "sameId";
//do the work to create the table here
let oldTable = document.getElementById('sameId');
oldTable.replaceWith(newTable);
I'm running into a problem when trying to add in the search functionality, showList().
It seems to bog down the client so much that Chrome wants to kill the page each time I type into the input field. I'm clearly a novice JS writer, so could I be running an infinite loop somewhere I don't see? Also, any advice to get the search functionality working properly would be hugely appreciated. I don't think I'm using the correct selectors below for the show/hide if statement, but I can't think what else to use.
$(document).ready(function(){
showList();
searchBar();
});
function showList() {
$("#show-records").click(function(){
$.getJSON("data.json", function(data){
var json = data;
$("show-list").append("<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
$("#show-list").append("<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>");
$("show-list").append("</table>");
}
//end getJSON inner function
});
//end click function
});
//end showList()
};
function searchBar() {
//AJAX getJSON
$.getJSON("data.json", function(data){
//gathering json Data, sticking it into var json
var json = data;
for(var i = 0; i < json.length; i++) {
//putting the json objects into var obj
var obj = json[i];
function contains(text_one, text_two) {
if (text_one.indexOf(text_two) != -1)
return true;
}
//whenever anything is entered into search bar...
$('#search').keyup(function(obj) {
//grab the search bar content values and...
var searchEntry = $(this).val().toLowerCase();
//grab each td and check to see if it contains the same contents as var searchEntry - if they dont match, hide; otherwise show
$("td").each(function() {
if (!contains($(this).text().toLowerCase(), searchEntry)) {
$(this).hide(400);
} else {
$(this).show(400);
};
})
})
}
});
};
body {
background-color: lightblue;
}
tr:first-child {
font-weight: bold;
}
td {
padding: 3px;
/*margin: 10px;*/
text-align: center;
}
td:nth-child(6) {
padding-left: 50px;
}
td:nth-child(7) {
padding-left: 10px;
padding-right: 10px;
}
#filter-count {
font-size: 12px;
}
<html>
<head>
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script language="javascript" src="process.js"></script>
<link rel="stylesheet" type="text/css" href="./mystyle.css">
</head>
<body>
<a href="#" id='show-records'>Show Records</a><br>
<label id="searchBar">Search: <input id="search" placeholder="Enter Specialist Name"></label>
<span id="search-count"></span>
<div id="show-list"></div>
</body>
</html>
Problem appears to be that you can't treat append as if it was a text editor and you are writing html.
Anything that gets inserted needs to be a proper element ... not a start tag, then some text...then a close tag.
We can however modify your code slightly to produce html strings and then add that at the end
$.getJSON("data.json", function(data){
var json = data;
var html="<table class='specialists'>")
for(var i = 0; i < json.length; i++) {
var obj = json[i],
tableFormat = "</td><td>";
html+= "<tr><td class=1>" +
obj.FIELD1 + tableFormat +
obj.FIELD2 + tableFormat +
obj.FIELD3 + tableFormat +
obj.FIELD4 + tableFormat +
obj.FIELD5 + tableFormat +
obj.FIELD6 + tableFormat +
obj.FIELD7 + tableFormat +
obj.FIELD8 + "</td></tr>";
}
html+= '</table>';
$("#show-list").html(html);
//end getJSON inner function
});
I have done a lot but nothing is working anymore, i would like to do when i click on td then it will take the id of that td and this id will go to the database and it will fetch all the childs of that id. now i want to append those childs to that td based on id. But when i click on the nested td it take the id of parent. Here is my code.
<script type="text/javascript" >
$(document).ready(function() {
var url = document.URL;
var parts = url.split("/");
var t = "";
for(var i=0; i<parts.length-1; i++) {
t += parts[i] + "/";
}
var which_li = "";
$("td").bind('click',function(e) {
e.stopPropagation();
which_li = $(this).attr("id");
$.ajax({
type: "POST",
data : {id : which_li},
cache: false,
url: t+"treeData",
success: function(data){
var childs = data.split(",");
var res = "<table style='border:1px solid #ddd'><tr>";
for(var i=0; i<childs.length; i++ ){
if(childs[i] != "") {
res += "<td id='"+childs[i]+"'>"+childs[i]+"</td>";
}
}
res += "</tr></table>"
$("td[id='" + which_li +"']").append(res);
}
});
});
});
</script>
Html table with default id that will be the root of all the id :
<table id="data" style=" margin:0 auto; border:1px solid #ddd" >
<tr>
<td id='2'>2</td>
</tr>
</table>
it's working only once but after that it only taking the id of parent td not child td.
Please help me to short out this problem.
e.stopPropagation();
Stop Propagation is also not working anymore.
here is my sql table
create table user_login (
id int not null auto_increment,
parent int not null
);
my table structure would be like this :
// this is my table strucutre
<table id="data" >
<tr>
<td id="2">2
<table>
<tr>
<td id="24">24
<table>
<tr>
<td id="29">29</td>
<td id="30">30</td>
</tr>
</table>
</td>
<td id="25">25</td>
<td id="26">26</td>
</tr>
</table>
</td>
</tr>
</table>
when i will click on id 2 then a table will append to td containing childs 24,25,26 and when i will click on 24 then a table will append to td containing childs 29,30 and so on.
but when i want to get the id of 24 or 25 then it's giving me id of parent td that is 2 every time. Please help me.
You are binding, but only to elements that exist when you bind. The event propagates up until it hits an element that was bound, at which point it is stopping propagation. What you need to do is bind the event to an element that exists, and then delegate that event to the one's that may or may not exist yet. Something like this should work:
$("body").on('click', 'td', function(e) {
e.stopPropagation();
which_li = $(this).attr("id");
$.ajax({
type: "POST",
data : {id : which_li},
cache: false,
url: t+"treeData",
success: function(data){
var childs = data.split(",");
var res = "<table style='border:1px solid #ddd'><tr>";
for(var i=0; i<childs.length; i++ ){
if(childs[i] != "") {
res += "<td id='"+childs[i]+"'>"+childs[i]+"</td>";
}
}
res += "</tr></table>"
$("td[id='" + which_li +"']").append(res);
}
});
});
Well first of all, you are not binding the click event to newly added td's.
Secondary, don't bind a click event to a tag, better give a class to a td, and bind the click to that class, this way you will have more flexibility.
Corrected your code a bit:
<script type = "text/javascript" >
$(document).ready(function() {
var url = document.URL;
var parts = url.split("/");
var t = "";
for (var i = 0; i < parts.length - 1; i++) {
t += parts[i] + "/";
}
var which_li = "";
$("#data").on('click', '.closed', function(e) {
var clicked_td = $(this);
$.ajax({
type: "POST",
data: {
id: clicked_td.attr("id")
},
cache: false,
url: t + "treeData",
success: function(data) {
var childs = data.split(",");
var res = "<table style='border:1px solid #ddd'><tr>";
for (var i = 0; i < childs.length; i++) {
if (childs[i] != "") {
res += "<td class='.closed' id='" + childs[i] + "'>" + childs[i] + "</td>"; //added a 'closed' class
}
}
res += "</tr></table>"
clicked_td.removeClass("closed").append(res); //removing the class, so the click event won't fire again
}
});
});
});
</script>
And your html (added a class to td):
<table id="data" style=" margin:0 auto; border:1px solid #ddd" >
<tr>
<td id='2' class='closed'>2</td>
</tr>
</table>
In the future, try to use dataType: 'json', and on your php side you can do something like:
...
$response = array('2', '3', '5', '10');
echo json_encode($response);
Using this method (and it is the right one if you takeajax seriously), you wond have to manually split the values, so instead of:
...
success: function(data) {
var childs = data.split(",");
var res = "<table style='border:1px solid #ddd'><tr>";
for (var i = 0; i < childs.length; i++) {
if (childs[i] != "") {
res += "<td class='.closed' id='" + childs[i] + "'>" + childs[i] + "</td>";
}
}
res += "</tr></table>"
clicked_td.removeClass("closed").append(res);
}
You can do this:
success: function(data) {
var res = "<table style='border:1px solid #ddd'><tr>";
$each(data, function()
res += "<td class='.closed' id='" + this + "'>" + this + "</td>";
});
res += "</tr></table>"
clicked_td.removeClass("closed").append(res);
}
Use live instead of bind if you want to bind to elements that might be added in the future since you are adding elements dynamically (http://api.jquery.com/live/) :
$(document).ready(function() {
var url = document.URL;
var parts = url.split("/");
var t = "";
for(var i=0; i<parts.length-1; i++) {
t += parts[i] + "/";
}
var which_li = "";
$("td").live('click',function(e) {
// snip
Also stopPropogation works fine.
Try
$(document).ready(function() {
var url = document.URL;
var parts = url.split("/");
var t = "";
for(var i=0; i<parts.length-1; i++) {
t += parts[i] + "/";
}
var which_li = "";
$("#data td:not(.child td)").bind('click',function(e) {
e.stopPropagation();
var which_li = $(this).attr("id");
$.ajax({
type: "POST",
data : {id : which_li},
cache: false,
url: t+"treeData",
success: function(data){
var childs = data.split(",");
var res = "<table class='child' style='border:1px solid #ddd'><tr>";
for(var i=0; i<childs.length; i++ ){
if(childs[i] != "") {
res += "<td id='child-"+childs[i]+"'>"+childs[i]+"</td>";
}
}
res += "</tr></table>"
$("#" + which_li).append(res);
}
});
});
});