I have a problem selecting an element from the html throght jQuery. It could be maybe the fact that the element i am trying to access is dynamically insterted throught getJson, but of course before executing the following js.
What can be the problem and how can be solved?
<table id="myTable">
<tbody>
<!-- inserted with getJson -->
<tr>
<td> <input type='checkbox' id="myInput0"> </td>
<td class="myClass">some text</td>
</tr>
<!-- other rows -->
</tbody>
</table>
var id = "myInput" + 0;
var text = $("#"+id).closest('tr').find('td.myClass').text();
alert(text)
I tried to recreate the scenario using getJSON and inserting an element dynamically, then you can do something like this:
$( document ).ready(function() {
const url = 'https://jsonplaceholder.typicode.com/todos/1';
$.getJSON( url, function( data ) {
$('#main').append(data.title);
});
});
codepen
hope it helps :)
Take a look at this Stack Overflow Q&A - How do I attach events to dynamic HTML elements with jQuery? - there are a few approaches you can take, but the jest of it is that you need to bind to the body or container of your element rather than the element itself.
Welcome to the community user21! Hopefully that info is helpful.
Related
I have a footable
. When I click on the plus to expand a row
I want to access with jQuery the yellow elements:
If I inspect the element the DOM looks like that after the click:
<table class="footable-details table">
<tbody>
<tr><th>
DOB (hide)
</th><td style="display: table-cell;">
10/16/1977
</td></tr><tr><th>
Description
</th><td class="someText" style="display: table-cell;">
Some description
</td></tr>
</tbody>
</table>
What I would like to do, is to set colspan="2" for td.someText and hide the <th>Description</th>. But I can't access td.someText
I tried to access it with
$('.footable').on('expand.ft.row', function(e, ft, row){
$(row.$details).find('td.someText'));
});
but he does not find anything. In fact, alert($(row.$details).html()); only returns
<td colspan="4">
<table class="footable-details table">
<tbody>
</tbody>
</table>
</td>
Any idea how to access the td with class someText after click?
Here is a jsFiddle
Note: This is not a duplicate of Footable and capturing the expand row event. The linked question is about how to access a row in general. This question is if I select it with the method from the API the content is not loaded correctly. The question helped me to get here, but does not to solve the here presented issue.
expand.ft.row event fires before it appends the dom content.so if you try to read the row content, it's not there.
The correct event for your case is expanded.ft.row which fires after appending the content.
$('.footable').on('expanded.ft.row', function(e, ft, row) {
alert($(row.$details).html());
});
check this demo
https://jsfiddle.net/bfmaredn/
I found this event by analyzing the source code from GitHub repository https://github.com/fooplugins/FooTable/blob/V3/src/js/classes/FooTable.Row.js
Use "async function", try the following code:
$(function() {
$(".footable").footable();
$('.footable').on('expand.ft.row', async function(e, ft, row) {
alert($(await row.$details).html());
});
});
Refer:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
I have a table with some data:
<table id="myTable">
<thead>
<tr>
<th><h1>Name</h1></th>
<th><h1>Picture</h1></th>
<th><h1>Likes</h1></th>
<th><h1>Time</h1></th>
</tr>
</thead>
<tbody>
***loop***
<tr>
<td>{placeholder1}</td>
<td><img src="{placeholder2}" alt=""></td>
<td>{placeholder3}</td>
<td>{placeholder4}</td>
</tr>
***end loop***
</tbody>
</table>
I have a js function who gets some data from server by POST request every 10 minutes. <tr></tr> block needs to be repeated several times.
HTML code become more and more complex and I need a solution with layouts and placeholders. I need a direction to search :)
All I need is:
Store <tr></tr> pattern with placeholders to insert it into my webpage. How could I achieve it with js?
How could I mark the places where I need data to be inserted?
Okay since you are using jQuery,
This may be your HTML
<table>
<tbody id="myTableBody">
<!-- Your elements will be placed here -->
</tbody>
</table>
I will assume you are using $.ajax or $.post in either of those, add a callback function property success
$.ajax({
// ... your properties,
success: function(data) {
// basic template for of your "tr"
var trTemplate = [
'<tr>',
'<td></td>',
'<td><img src="" alt=""></td>',
'<td></td>',
'<td></td>',
'</tr>'
].join('')
// get the tbody elemen
var $myBody = $('#myTableBody')
// if you want to clean up the current content of $myBody,
// if it is not the case just remove the following line
$myBody.empty()
// assuming data is an array of elements / entities
data.forEach(function(element){
var $tr = $(trTemplate)
$tr.find('td').eq(0).text(element.placeholder1)
$tr.find('img').attr('src', element.placeholder2)
$tr.find('td').eq(2).text(element.placeholder3)
$tr.find('td').eq(3).text(element.placeholder4)
$myBody.append($tr)
})
}
})
This is example of how you could do it, there are many ways to improve this for performance and so on. Please use it only as reference
If you're using jQuery then this is pretty straightforward. You need to id your elements so that you can reference them individually. Say you start with:
<tr id="tr-0" >
content...
</tr>
and then in javascript..
var id = $('#tr-0').attr('id');
var num = parseInt(id.substring(3));
num++;
$('#tr-0').after('<tr id='+num+'>content...</tr>');
obviously you need to figure how you're getting the content for each row but hopefully you can see that it wouldn't be too hard to fill each row with custom data.
Although you can use jQuery, simpler ways exist. jQuery will require you to add additional steps that aren't really necessary. If you want to use as few Javascript packages as possible, go with jQuery.
But, I highly recommend Vue.js for Laravel projects. There are instructions from Laracasts on how to set it up. But, I have created a jsfiddle with a working set of Vue.js with the v-for directive. Checkout the JSFiddle here.
If you have questions, I'll answer as much as I can.
I have a filterable table containing a collapsible list in a column. The collapsible contains another table. Sample of the situation.
The problem is that when anything is written to filter only the required items, the inner table also gets filtered. Is there a way to avoid this.
Suggestions about how else to display something like this are also welcome.
If you want to filter only from the Name column, you can try to use below code:
$('#filter').keyup(function () {
var stringValue = $(this).val();
$("#outer-table tr.row").each( function( index ) {
$(this).hide();
$(this).find(".panel-title a:contains("+stringValue+")").parents("tr").show();
});
});
EDIT: I have tested the new code above, it works as expected.
HTML changes, easier to get ONLY every <tr> that are part of your outer-table:
Change your outer-table tag from <tbody class="searchable">, into this, <tbody id="outer-table" class="searchable">
Then add a selector to every <tr> inside outer-table but NOT inside inner-table, like this:
</tr>
<tr class="row">
<td><div id="collapsibleMain2" class="panel-group">
</tr>
<!-- and so on -->
For more info about the jQuery functions that I used above:
contains
each
hide
I am attempting to create a script to add another row in a table with specific html content. The problem is that i'd like to use the same script on each section of a rather long form. Selecting the table id without having to do so with the exact table name seems to be escaping me.
The point here is to just hit the "add" button and it will add an additional item of whatever section that button is in. But before i can have it add I need to be able to select the correct item (the table id) without actually using "getElementById".
I've scoured for an answer and being still pretty new to web javascripting, i'm guessing i'm just not understanding something or attempting the wrong method... any assistance would be greatly appreciated.
HTML
<div id="divOne">
<table id="myTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
</table>
<br />
<button onclick="myFunction()">Test ONE</button>
</div>
<br />
<div id="divTwo">
<table id="testTable">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
</table>
<br />
<button onclick="myFunction()">Test TWO</button>
</div>
jquery
function myFunction() {
var x = event.currentTarget.parentNode.getAttribute('id');
alert(x); //to test its grabbing correct div THIS ONE WORKS
var child = x.getElementsByTagName('table').getAttribute('id');
alert(child); //to test its grabbing correct THIS ONE DOESNT
}
There are two issues need to be fixed:
According to your implementation, x is the id of the parent div (string value), you can't invoke the 'getElementsByTageName('table') on it. You should get the element reference
getElementsByTagName() will return a HTMLCollection, try to access them like this: children[index]
HTML
<div id="div1">
<table id="ans"></table>
<button onClick="test(event)">test</button>
</div>
JS
function myFunction(e){
var target = e.currentTarget.parentNode;
//fetch id
console.log(target.getAttribute("id"));
//fetch table id
console.log(target.getElementsByTagName("table")[0].getAttribute("id"));
}
Here is the jsfiddle demo
Did you already try jQuery? It has some nice methods which make life easier. You may want to choose .closest() which selects an element depending on your current context.
Also, there's no need to use the awkward getElementById anymore...
You have a bug in your myFunction. This should help: http://jsfiddle.net/2wA38/
In this case, you want to find the sibling table element; you can navigate the DOM using previousSibling until you reach the element:
function myFunction() {
var node = event.currentTarget,
x = node.parentNode.id;
console.log(x);
while (node && node.tagName != 'TABLE') {
node = node.previousSibling;
}
if (node) {
console.log(node.id);
}
}
I want to list files from mysql table to a webpage in php. For this i use tables so that i have more regular view. Now there are n numbers of tables on a page. This n is depending upon a mysql query. I am able to list the files on the page. But if numbers of rows in table get increased and value of n is also get increased then my page length will be very long. So i want to give a tree view to each table. Like there will be a button over each table with value '+'. when i click on it the value get change to '-' and that table should be visible.
Here what i tried
<script type="text/javascript">
$(document).ready(function(){
$(".show").html("<input type='checkbox'>");
$('.tree td').hide();
$('th ').click( function() {
$(this).parents('table').find('td').toggle();
});
});
<table width="100%" class="tree">
<tr width="20px"><th colspan="2" class="show"> </th></tr>
<tr>
<td width="50%"><b>Name</b></td>
<td width="50%"><b>Last Updated</b></td>
</tr>
while($row = $result_sql->fetch_assoc())
{
<tr>
<td width='50%'><a href='http://127.0.0.1/wordpress/?page_id=464&name_file={$row['name']}&cat={$cat}&sec={$sec}' target='_blank'>{$row['title']}</a></td>
<td width='50%'>{$row['created']}</td>
</tr>
}
</table>
This is not exact code.
as you can see i am able to do it but i am using a chackbox. i want to have a button with value + or - . There is one problem with this code. The line in which checkbox is showing if i click on it the table is expanded means it taking the entire row not only the checkbox. So anybody can help me with this?
Thanks
I know that this is a code sample, in the future try to provide a jsFiddle to make it easier for people to help. If you want to use +/-, you can make a minor modification like my example
<th colspan="2" width="100%"><span class="show"></span></th>
I basically added the show class to a span within the <th> and attached a click handler on it as well. When you click on it, it will toggle the <td> within the parent <table>... in addition, it will check the text-value in the <th> and inverse it
$('.show').click(function () {
$(this).parents('table').find('td').toggle();
$(this).text() == '+' ? $(this).text('-') : $(this).text('+');
});
Since you don't need a checkbox and you are using a <span>, it won't wrap across the entire <th>. Was this what you were looking for?
Get solution
<script type="text/javascript">
$(document).ready(function(){
$(".show").html("<input type='button' value='+' class='treebtn'>");
$('.tree td').hide();
$('.treebtn ').click( function() {
$(this).parents('table').find('th').parents('table').find('td').toggle();
if (this.value=="+") this.value = "-";
else this.value = "+";
});
});
It is working fine the way i wanted.