Show/Hide Child Nodes using jQuery - javascript

I am trying to show child nodes(If option selected is 'Yes') based on the indent value. indent0-> parent node , indent1 - child node.
Sort-order is the order in which nodes are placed in DB.
$( "body" ).on( "click", ".js-show-aspects", function(event) {
var displayLabel = $(this).data('meta-value');
var sort_order = $('.js-data-selector.active:first').data('sort-order');
var indent = $('.js-data-selector.active:first').data('indent');
var rowCount = $('#show_aspects td').length;
for (var i=0;i<rowCount;i++)
{
var hasindent0 =$(this).next().hasClass("indent0");
if((displayLabel=='Yes') && (hasindent0== false)) {
child1 = $("table tr td").filter(function() {
return $(this).prop("class").match(/indent/)});
child = child1.addClass(function (index){ return "sort-order"+(sort_order+1)});
}
}
});
HTML
In the below html, $aspects gets all the nodes from DB,
<tbody>
<? foreach($aspects as $a) { ?>
<tr id="show_aspects" class="js-data-selector
<?=($a['active'] == 0) ? "text-warning" :""; ?> "
data-sort-order="<?= $a['sort_order'] ?>"
data-indent="<?= $a['indent']?>" align="left"
data-taxonomy-id="<?=$a['taxonomy_id']?>">
<td class="indent<?=$a['indent']?>
sort-order<?=$a['sort_order']?>"
data-indent="<?= $a['indent']?>">
<? if($a['active'] == 0) {
echo '<strong class="pull-right text-warning">Inactive</strong>';
} ?>
<?=$a['aspect_label']?> :
<span class="aspect-data" data-taxonomy-id="<?=$a['taxonomy_id']?>"></span>
</td>
</tr>
<?}?>
</tbody>
But I am unable to get the child nodes displayed. Any idea how to sort this out?
Edited the question with the HTML content..

It is difficult to understand exactly what you are trying to do with the question in its current form, but if you want to hide or show child nodes with jQuery, it can be done with $("#id").children().hide(); and $("#id").children().show();.
(Where "#id" is the ID of the parent DOM node.)
children() also takes a selector as an argument in case you only want specific children hidden/shown: http://api.jquery.com/children/
(If you clear up your question a bit, it would be possible to give a more appropriate answer)

Related

Ajax load() loads only once [duplicate]

This question already has answers here:
How do I attach events to dynamic HTML elements with jQuery? [duplicate]
(8 answers)
Closed 4 years ago.
I have a school project of making some page, which have to add, remove, modify and sort data from mysql. And i need, to refresh section 3 called "jezdci" or just the table in it. I using load() for that. But its loads only once, when i click on that a second time, nothing happend. Then i have to again refresh the page. And i need to load it again and again. Do someone know, where is a mistake?
You can see it at http://188.75.190.236/host/xhrazd7/www/ZP%20Hrazdira/index1.php
HTML:
<section>
<?php include "vypis.php"; ?>
</section>
JS:
$(document).ready(function(){
$(".serad > td").click(function(){
y = $(this).index();
$("section:eq(2)").load("vypis.php",{
serad:y
},);
alert("Loaded index of td on click with value: "+y);
});
});
PHP:
<?php
include "conn.php";
if(!empty($_POST["serad"])){
$serad = $_POST["serad"];
echo "<script>alert(\"variable succefully sended to PHP with value of \"+$serad);</script>";
}else{
$serad=8;
}
if($serad==0) $SQLprikaz = "SELECT * FROM ZP ORDER BY ID";
if($serad==1) $SQLprikaz = "SELECT * FROM ZP ORDER BY jmeno";
if($serad==2) $SQLprikaz = "SELECT * FROM ZP ORDER BY prijmeni";
if($serad==3) $SQLprikaz = "SELECT * FROM ZP ORDER BY vek";
if($serad==4) $SQLprikaz = "SELECT * FROM ZP ORDER BY bydliste";
if($serad==5) $SQLprikaz = "SELECT * FROM ZP ORDER BY ulice";
if($serad==6) $SQLprikaz = "SELECT * FROM ZP ORDER BY kategorie";
if($serad==7) $SQLprikaz = "SELECT * FROM ZP ORDER BY zaplaceno";
if($serad==8) $SQLprikaz = "SELECT * FROM ZP";
$result = $conn->query("$SQLprikaz");
echo "<table>";
echo"<tr class=\"serad\"> <td><p>Pořadí</p></td> <td><p>Jméno</p></td> <td><p>Příjmení</p></td> <td><p>Věk</p></td> <td><p>Bydliště</p></td> <td><p>Ulice</p></td> <td><p>Kategorie</p></td> <td><p>Zaplaceno</p></td> </tr>";
while($zaznam=$result->fetch_array(MYSQLI_NUM)){
echo"<tr> <td>$zaznam[0]</td> <td>$zaznam[1]</td> <td>$zaznam[2]</td> <td>$zaznam[3]</td> <td>$zaznam[4]</td> <td>$zaznam[5]</td> <td>$zaznam[6]</td> <td>$zaznam[7]</td> </tr>";
}
echo "</table>";
?>
And sorry for my poor english :D
PS: Když by se tu našel někdo hodný z Česka nebo Slovenska a měl chvíli času, budu rád, když mě zkontaktujete. Dík < some boring notes in my native language
and Thanks a lot!
As haï_uit mentioned it's because there's no event attached to the next table. You can get around this by targeting an element that will always be in the page and using the on Method like so:
$(document).ready(function(){
$("body").on("click", ".serad > td", function(){
y = $(this).index();
$("section:eq(2)").load("vypis.php",{
serad:y
},);
alert("Loaded index of td on click with value: "+y);
});
});
The problem is here :
$(document).ready(function(){
$(".serad > td").click(function(){
y = $(this).index();
$("section:eq(2)").load("vypis.php",{
serad:y
},);
alert("Loaded index of td on click with value: "+y);
});
});
After your ajax load successfully, your old table which has "td" attached to click event is replaced by new table which doesn't have "td" with click event. So in your ajax load function, you must add click event for your table again after it load successfully. Another solution is just replace the data rows, not the whole table.
First option, you can add the click event again :
$(document).ready(function(){
var tabs = $('.serad > td');
tabs.click(changeTabs);
function changeTabs() {
y = $(this).index();
$('section:eq(2)').load('vypis.php',{
serad:y
}, function () {
tabs = $('.serad > td');
tabs.click(changeTabs);
});
}
}
Second option, only load table content:
Change your html file to this :
<section>
<table>
<tbody id="tabs">
<tr class="serad">
<td>
<p>Pořadí</p>
</td>
<td>
<p>...</p>
</td>
</tr>
</tbody>
<tbody id="content">
<?php include "vypis.php"; ?>
</tbody>
</table>
</section>
in php file, only echo the rows :
while($zaznam=$result->fetch_array(MYSQLI_NUM)){
echo"<tr> <td>$zaznam[0]</td> <td>$zaznam[1]</td> <td>$zaznam[2]</td> <td>$zaznam[3]</td> <td>$zaznam[4]</td> <td>$zaznam[5]</td> <td>$zaznam[6]</td> <td>$zaznam[7]</td> </tr>";
}
and finally, in your script :
$(document).ready(function() {
$('.serad > td').click(function () {
y = $(this).index();
$.post('vypis.php', { serad: y }, function (response) {
$('#content').html(response);
});
});
});

How can i implement search like ctrl+f with jquery

Hi i am trying to search on page table tbody, the search is should be like ctrl + F search this my html and php code:
Please refer the image and link linked below for the sources.
<table>
<thead>
<tr><td><input type="text" placeholder="Search Student id="searchStudent"> </td>
<td></td><td></td><td></td><td></td><td></td></tr>
</thead>
<tbody>
<tr>
<td>
<span><img src="<?php echo $gdScoreData['profile_pic']; ?>"/></span>
<p><?php echo $gdScoreData['student_fname'];?> <?php echo $gdScoreData['student_lname'];?></p>
<p><b>Hallticket</b> : S<?php echo $gdScoreData['student_pid']; ?>J<?php echo $jobID; ?></p>
</td>
<td></td><td></td><td></td><td></td><td></td></tr>
1st tr will close here php code is the above one in html it looks like shown in image:
<tr><td><span><img src="profile_pic/first_1479536519.jpg" width="50" /></span><p>Robert Smith</p><p><b>Hallticket</b> : S27J2</p></td></tr>
</tbody>
</table>
This my javascript code to search like ctrl + F
/* Search Student like ctrl+f start */
$("#searchStudent").on("keyup", function() {
var value = $(this).val();
console.log(value);
$("table tbody tr").each(function(index) {
if (index !== 0) {
$row = $(this);
var id = $row.find("td:first").text();
if (id.indexOf(value) !== 0) {
$row.hide();
}
else {
$row.show();
}
}
});
});
/* Search Student like ctrl+f end*/
Here is the source from where i have tried:
Source JS
i have modified your js fiddle code now it working jsfiddle.net/rFGWZ/3406/
$("#search").on("keyup", function() {
var value = $(this).val();
if(value!='') {
$("table tbody tr").hide();
}else{
$("table tbody tr").show();
}
$('table tbody tr td:contains("'+value+'")').parent('tr').show();
});
Basically your code is working but it is not picking up elements inside your tag
try adding the following:
var id2 = $row.find("b:first").text();
and changing this:
if (id2.indexOf(value) !== 0) {
Then search based on the bold content and it should work
You could try it like this and search on each part individually:
$id = $row.find("td:first");
var id2 = $id.find("b:first").text();
var id3 = $id.find("p:first").text();
if (id2.indexOf(value) !== 0 && id3.indexOf(value) !== 0) {
$("#searchStudent").on("keyup", function() {
var value = $(this).val();
if(value!='') {
$("table tbody tr").hide();
}else{
$("table tbody tr").show();
}
$('table tbody tr td:contains("'+value+'")').parent('tr').show();
});
I have resolved with this help.

sort parent element based on contents of child element - javascript/jquery

I have a monthly calendar which displays days with events happening in this day. This is how generated HTML looks like:
<table class="event-cal">
<tbody>
<tr class="eventcont event-93">
<td class="eventtime">19:00</td>
<td><a class="calendar-title" href="#>Event title</a><br></td></tr>
<tr class="eventcont event-237">
<td class="eventtime">13:00</td>
<td><a class="calendar-title" href="#">Event 2 title</a><br></td></tr>
</tbody>
</table>
What I want to do is to order tr.eventcont elements based on contents of .eventtime child element. Ordering has to be done within .event-cal element which contains these particular .eventcont elements because I will have several .event-cal elements in the page.
Here is the code I have so far but what it does it takes all tr.eventcont elements from page and pastes them all into each .event-cal table.
$( document ).ready(function() {
var list = $(".event-cal").find(".eventcont");
list.sort(sortDesc);
$(".event-cal").html("");
$(".event-cal").append(list);
});
function sortDesc(a, b){
var test1 = jQuery(a);
var test2 = jQuery(b);
return test1.find(".eventtime").text() > test2.find(".eventtime").text();
}
You need to run your function for each table using jquery.fn.each
$('.event-cal').each(function() {
var table = $(this),
list = table.find('.eventcont').sort(sortDesc);
table.empty().append(list);
});
Check this fiddle
$(".event-cal").each(function(){
var events=$('tr',this);
events.sort(function (a, b) {
a = parseInt($('.eventtime',a).text().replace(':',''));
b = parseInt($('.eventtime',b).text().replace(':',''));
if(a > b) {
return 1;
} else if(a < b) {
return -1;
} else {
return 0;
}
});
$(this).html(events);
});

How to achieve this without refreshing the page using jQuery?

I have a web page that populates a table via jQuery.
Since I only want to change classes of a particular <td> element I used replaceWith. This worked well on the first search, but I realized that I could not asynchronously perform another search without first refreshing my page. I then tried html instead of replaceWith. This worked well, but crammed all the new <td> into one <td> that has the specified id.
How can I achieve this without refreshing the page so that I can get the <td> elements well distributed?
Before updating:
<table>
<tr>
<td>first row</td>
<td>measure1</td>
<td>measure2</td>
<td>measure3</td>
<td>measure4</td>
<td> </td>
</tr>
<tr>
<td>First row</td>
<td id="no_rec" colspan="4"> No record to display!</td>
<td>More+</td>
</tr>
</table>
After updating I expect to have a table of the format:
<table>
<tr>
<td>first row</td>
<td>measure1</td>
<td>measure2</td>
<td>measure3</td>
<td>measure4</td>
<td> </td>
</tr>
<tr>
<td>First row</td>
<td class="new"></td>
<td class="new"></td>
<td class="new"></td>
<td class="new"></td>
<td>More+</td>
</tr>
</table>
My JavaScript:
$('#mybutton').click(function()
{
$.post
(
'search.php',
{
regNo: $("#regNo").val(),
datepicker: $(".datepicker").text()
},
function(data)
{
$.each(data, function(i)
{
var tm = data.time;
add_html='';
for (i=0; i<4; i++)
(i === 0 || i === 2)
? add_html += '<td class="new"></td>'
: add_html += '<td></td>';
$('#no_rec').replaceWith(add_html);
});
},
'json'
);
});
My JsFiddle Attempts
What I did was add id=results to the tr so that I could find and store all td tags and then manipulate them accordingly.
See working jsFiddle demo
All notes are left in the comments of the jQuery, but one that I should mention here is that I added a simulateData() function that basically allows you to click the Update button as many times as you want to see how the code will handle different data that's returned.
HTML
<table border="1">
<tr>
<td>first row/measures</td>
<td>measure1</td>
<td>measure2</td>
<td>measure3</td>
<td>measure4</td>
<td>measure5</td>
</tr>
<tr id="results">
<td>First row</td>
<td colspan="4">No record to display!</td>
<td>More+</td>
</tr>
</table>
<button>Update</button>
jQuery
var noRecord = "<td colspan=\"4\">No record to display!</td>",
currentTime = 0;
$( "button" ).click( function ()
{
var $results = $( "#results" ), // Get the TR.
$tds = $( "#results" ).find( "td" ), // Get the TDs within the TR.
data = simulateData(); // Simulate data.
// Check to see if data was returned.
if ( data === undefined )
{
// Data was not returned.
if ( $results.html().indexOf( noRecord ) === -1 )
{
// Results TR has previous values that need to be removed.
for ( i = 1; i < 5; i++ )
$( $tds[i] ).remove();
// Add back the [No record to display!] TD.
$( noRecord ).insertAfter( $tds[0] );
}
}
else
{
// Data was returned.
$.each( data, function ( i )
{
// Store the current data.
var tm = parseInt( data.time );
// Check to see if the Results TR has previous values or not.
if ( $results.html().indexOf( noRecord ) > -1 )
{
// Results TR does not have previous values.
var html = "";
// Generate new TDs.
for ( i = 1; i < 5; i++ )
html += "<td class=\"new\">" + tm + "</td>";
// Remove [No record to display!] TD and replace with new TDs.
$( $tds[1] ).replaceWith( html );
}
else
{
// Results TR has previous values so we need to loop
// through each existing TD replacing its class and value.
for ( i = 1; i < 5; i++ )
{
if ( i != tm )
{
// Change class to "new" and add stored data value.
$( $tds[i] )
.removeClass( "rr" )
.addClass( "new" )
.text( tm );
}
else
{
// Change class to "rr" and add "ee" value.
$( $tds[i] )
.removeClass( "new" )
.addClass( "rr" )
.text( "ee" );
}
}
}
});
}
});
// This simulates the async calls to search.php to generate
// different times on each click of the Update button.
function simulateData()
{
// Increment our simulated time.
currentTime++;
if ( currentTime > 4 )
{
// Start over by resetting our incrementer.
currentTime = 0;
// Simulate a call that doesn't return data.
return undefined;
}
else
{
return { "time": currentTime }
}
}
Since I only wants to change classes of perticular element I used replaceWith
replaceWith() method entirely replaces all matching elements with the new content.
for simply changing the css class you can use
.addClass()
adds the specified class to matched elements
.removeClass()
removes the specified class from matched elements
.toggleClass()
adds the class if it's not applied, removes it if it's already applied

How to delete a created element in JavaScript?

Hello I have a piece of code that allows me to add an author.
I have a problem, I can't seem to delete the created node in my table
This is the worst frustration in my life. I could not seem to delete it.
I also have notice that every time I inspected the element I could not see the
new created element from the source. But when I view it on firebug I can actually see it there.
Adding an input element and appending it on the table works fine for me.
I am just very new to JavaScript and to this web thingy and deleting a CREATED ELEMENT via .createElement is where I am stuck at.
here is my code
<script>
var ctr = 1;
function showTextBox()
{
// is the table row I wanted to add the element before
var target = document.getElementById('bef');
var tblr = document.createElement('tr');
var tbld1 = document.createElement('td');
var tbld2 = document.createElement('td');
var tblin = document.createElement('input');
tblin.name = 'Author' + ctr;
tblin.id = 'Author' + ctr;
tblin.placeholder = 'add another author';
tbld1.appendChild( document.createTextNode('Author' + ctr ) );
tbld2.appendChild( tblin );
tblr.appendChild( tbld1 );
tblr.appendChild( tbld2 );
target.parentNode.insertBefore( tblr , target );
ctr++;
}
function hideTextBox()
{
var name = 'Author'+ctr;
var pTarget = document.getElementById('tbhold');
var cTarget = document.getElementById( name );
alert( cTarget ); // this one return null? Why? I have created id="Author1"
// viewing this code on source make the created elem to not appear
}
</script>
Am I doing something wrong? I really need help. This is for my project at school.
Is there any way I could delete it. I created that node and I want it to be deleted when I click something.
Also I prefer to stay with JS not with JQuery or other JStuff and I am disregarding compatibility for now because this is just a sample in my dummy form. I will deal on that later.
EDIT
In case you need the actual form here it is
<form enctype="multipart/form-data" action="process/" method="POST" />
<h3>Book Upload</h3>
<table border="2" id='tbhold'>
<tr>
<td>Title</td>
<td><input type="text" id="book_title" name="book_title" /></td>
</tr>
<tr>
<td>Author</td>
<td><input type="text" id="book_author" name="book_author" /></td>
</tr>
<tr id="bef">
<td colspan="2">
add author
remove
</td>
</tr>
</table>
</form>
Thank you very much!
Try this function:
function removeElements(elements){
for(var i = 0; i < elements.length; i++){
elements[i].parentNode.removeChild(elements[i]);
}
}
Then you can do this:
removeElements(document.querySelectorAll('#tbhold tr'));
function hideTextBox(){
var name = "Author" + (ctr - 1);
var pTarget = document.getElementById('tbhold');
var cTarget = document.getElementById(name);
var tr = cTarget.parentNode.parentNode;
tr.parentNode.removeChild(tr);
ctr = ctr - 1;
}
Here is a demo
every time I inspected the element I could not see the new created element from the source. But when I view it on firebug I can actually see it there.
If you change the DOM, you of course do not change the HTML source markup. Only the DOM inspector will show you the changes.
var name = 'Author'+ctr;
var cTarget = document.getElementById( name );
alert( cTarget ); // this one return null? Why? I have created id="Author1"
Yes, you created it using your showTextBox function. But that did also increment the ctr to 2, so that you now are looking for Author2 which obviously does not exist. So put a ctr--; before it and it should work.

Categories

Resources