Jquery thinks table is empty - javascript

Please consider the following code:
CODE:
$(document).on("click", "#add_new_item_ingredient", function() {
$(this).siblings("#ingredients_table").append('<tr><td style="width:20%"> <input type="text" id="option_item_costs_2" class="form-control" placeholder="£2.50"> </td><td style="width:50%"> <input type="text" id="option_item_desc_2" class="form-control" placeholder="Ex. Extra tomato"> <input type="hidden" id="option_item_id_2" value="-1"> </td></tr>');
});
$(document).on("click", "#remove_new_item_ingredient", function() {
$(this).siblings("#ingredients_table tr").each(function(index) {
alert("!");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-striped notifications" id="ingredients_table">
<tbody>
<tr>..</tr>
<tr>..</tr>
<tr>..</tr>
</tbody>
</table>
<button class="btn_1" id="add_new_item_ingredient">+ Ingredient</button>
<button class="btn_1" style="background:#C70000;" id="remove_new_item_ingredient">- Ingredient</button>
Adding new rows with the first button works great, however when I attempt to remove the last tr element from the same table, it does nothing. I am now attempting to alert, for each tr element found, but I get no alerts. I have tried getting the table row count which always returns 0, and also attempted trying to get the element with #ingredients_table >tbody >tr
I can confirm that both of the click events are firing correctly, and I can correctly select the table element, just none of the rows within.
Any advise would be greatly appreciated.

It's because the button #remove_new_item_ingredienthas no tr siblings.
You either select the table first and then use find to get the tr's:
$(this).siblings("#ingredients_table").find("tr").each(function(index) {
or use the:
$("#ingredients_table tr").each(function(index) {
which is better in redability.
And as #T.J.Crowder mentioned:
You have two tbody elements in your table (neither of them closed, probably a typo)
You're appending the rows to the table, not the tbody

Remove's handler $.siblings looks for tr elements on the same level as button, which is not the case. trs are in table, that is 2 levels down. So just modify your call to $(this).siblings("#ingredients_table").find('tr')

Related

Deleting contents of last cell of html table row

I have an html table that includes rows:
<tr id="firstInRow"><td></td><td><input name="longP1" id="longP1" type="text" style="width: 70px"></td><td><input name="latP1" id="latP1" type="text" style="width: 70px"></td><td>(upper left)</td></tr>
<tr id="secInRow"><td></td><td><input name="longP2" id="longP2" type="text" style="width: 70px"></td><td><input name="latP2" id="latP2" type="text" style="width: 70px"></td><td>(lower right)</td></tr>
which creates a table like this:
latLongTable
I have already created an add row function that works, and I am trying to delete the contents of the last cells in that function. I want to remove the text "(upper left)" and "(lower right)". I tried a couple of ways, including:
var rowIn1 = document.getElementById("firstInRow");
rowIn1.deleteCell(-1);
But it doesn't work.
You can use .remove() function of jQuery.
For example:
$("#firstInRow").find("td:last-child").remove();
This will find the last column (td) of the row with id firstInRow and remove it from DOM. You can remove the other cell using the same method.
If you want to remove the content only then use:
$("#firstInRow").find("td:last-child").text('');
This will not remove the last column from DOM, instead it will clear the content from last column.
$("#clear").on("click", function() {
$("#firstInRow").find("td:last").text("");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<table border="1" cellpadding="5">
<tr id="firstInRow">
<td>First</td>
<td>Last</td>
<td>Content to clear</td>
</tr>
</table>
<button type="button" id="clear">Clear last column</button>
</body>

Hide tr element from click within it

I've got a table structure (see snippet below) and my goal is to hide a tr element once I click on the span that reads delete. I need the specific tr where that delete is contained.
I already got a listener for the click event on the last span, the one that says "delete" working.
I've got several tr elements, is it possible to hide the tr where the span is contained (and therefore, all the contents)?
$(".delete_pm").click(function () {
alert('hey');
$(this).closest( "tr" ).hide(); // tried this from answers below but no luck, as you can see here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<tr>
<td>
<input type="radio" name="credit-card" value="fjxtnw" checked />
<strong>555555******4444</strong> (MasterCard)
<label>(default)</label>
<span id="fjxtnw" class="delete_pm"><label>delete</label></span>
</td>
</tr>
You can use .closest to search the parents. Provide it with tr as the selector, then simply hide it.
$(".delete_pm").click(function() {
$(this).closest("tr").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="radio" name="credit-card" value="fjxtnw" checked />
<strong>555555******4444</strong> (MasterCard)
<label>(default)</label>
<span id="fjxtnw" class="delete_pm"><label>delete</label></span>
</td>
</tr>
</table>
have you try this,
$(".delete_pm").click(function() {
$(this).closest("tr").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td>
<input type="radio" name="credit-card" value="fjxtnw" checked />
<strong>555555******4444</strong> (MasterCard)
<label>(default)</label>
<span id="fjxtnw" class="delete_pm"><label>delete</label></span>
</td>
</tr>
</table>
closest will give you the nearby parent with the matching selector.
hide will not remove the item from the DOM.If you want that also, you may chain the remove method call also.
$(".delete_pm").click(function () {
var _this=$(this);
_this.closest("tr").hide().remove();
});
Here is a working jsfiddle

Select elements in each child tables one by one

I have the following html which is basically a parent table with some child tables inside it,
<table id="roottable" class="tablemain" cellspacing="0" cellpadding="0">
<tbody>
<tr>
<td></td>
<td>
<table class="intable" align="center" border="0">
<tbody>
<tr>
<td class="chn" colspan="2" align="center">
<div>
<div class="mparent">
<div class="checkbox">
<input type="checkbox" id="ch243" name="ch243" value="243">
<label for="ch243"></label>
</div>
<div class="chtext">Category</div>
</div>
</div>
</td>
</tr>
<tr>
<td>Param two</td>
<td>
<div class="checkbox">
<input type="checkbox" id="ch244" name="ch244" value="244">
<label for="ch244"></label>
</div>
</td>
</tr>
</tbody>
</table>
......
......
<table class="intable" align="center" border="0">
......
......
What I need to do is access all checkboxes of the nested table, for each table. That is get the checkboxes inside the first nested table, perform some operations with it, move to the next nested table do the same with the checkboxes inside it.
I can access individual tables like below with their id,
$('#tableid').find('input[type="checkbox"]').each(function () {
});
This works, but the tables are auto generated from db and the id is not known beforehand, also, the number of tables may vary, so I have no option other than selecting the parent table and then look for every child tables inside it one by one ... I have tried this ...
$('table').each(function(){
$(this).find('input[type="checkbox"]').each(function () {
// DO STUFFS WITH CHECKBOXES
});
But it doesn't work... How do I go about this? Thanks.
$('table tr td').each(function(){ // this line is for main outer table
$(this).children('table').each(function () { //this will iterate all the child table
$(this).find('input:checkbox').each(function(){ //this will find checkbox inside each table
//Your Stuff
});
});
});
NOTE :- I m not using id selector here because questioner mentioned that he doesn't know id's beforehand.
Working Demo
Working Demo
Your final code block looks acceptable, except that you haven't prevented the table selector from also selecting the outer table. As written, this would cause each set of checkboxes to be considered twice - once as part of its own table and again (actually first) as descendants of the outer table.
Try a more specific selector:
$('#roottable .intable').each(...)
I would do something like this:
$('#roottable').find('.intable').each(function(index, elt) {
// operate now on each "child table"
var $childTable = $(elt);
$childTable.find('input[type="checkbox"]').each(function(i, cb){
// Do your stuff with the checkoxes of the current ".intable" table
});
});
Just use:
var tableInputs = {};
$('#roottable input[type="checkbox"]').each(function () {
var id = $(this).closest('table').attr('id');
var name = $(this).attr('name');
tableInputs[id] = {};
tableInputs[id][name] = $(this).val();
});
This will select all checkboxes that are a child of a table.
EDIT if you need to group just find the id of the closest parent table and use that as an index for an object. You end up with one large object with all the id's as properties, while using only one each loop.

Accessing different types of element

I have a table with few rows. Each rows has header, data and hidden field. Data column can have either text or textarea.
<table id="knowledgeTreeTable" class="custom">
<tbody>
....................
<tr>
<th class="">What is the name of the party?</th>
<td class="">
<textarea id="ktField_7" class="ktEdit" type="text"></textarea>
</td>
<input id="ktField_7H" type="hidden" value="Unique contested">
</tr>
<tr>
<th class="">What is the name of the opposing party?</th>
<td class="">
<input id="ktField_8" class="ktEdit" type="text" style="width: 97%;">
</td>
<input id="ktField_8H" type="hidden" value="Query">
</tr>
......................
</tbody>
</table>
I am able to read the content of header and hidden field but not sure how to read data column as it can have two different types of element.
$("#knowledgeTreeTable tr").each(function() {
alert($('th', this).text());//OK
//alert($('td > [input, textarea]', this).val()); // This is not OK.
alert($('input', this).val());//OK
});
You can't group selectors like
td > [input, textarea]
Instead, use
td > input, td > textarea
Just as you would in a CSS selector, look for both:
alert($('td > input, td > textarea', this).val());
Although since you're using the same class for both, I'd be inclined to use:
alert($('td > .ktEdit', this).val());
Whenever you're trying to access a child element in a loop like this, you need to establish what the common factors between each element is. In this case they are different tags with different names, but they both have the ktEdit class, and both have type="text" (which I don't believe is actually applicable to textareas).
In this case, the common variable is the class name, so you can use that as your selector. As long as you target your parent loop correctly, it won't matter if you use that class on other elements throughout the page:
$("#knowledgeTreeTable tr").each(function() {
alert($('.ktEdit', this).val());
});

JQuery click event to add or remove table rows

I have a table that has plus or minus glyph-icons at the top that allow the user to add or subtract rows. The code I have works but if the user clicks the minus button too many times it will eat the whole table.
What I have tried is to add an unique ID tag to the rows I add and only delete the TRs with the ID but if 2 rows are added and the minus is pressed both rows will be deleted at once, I only want to delete one row at a time. Note: the code below does not reflect this attempt.
Glyphicons:
<div class="well" style="margin-bottom:0px;" id="addrow">
<span class="glyphicon glyphicon-plus" id="add"></span>
<span class="glyphicon glyphicon-minus" id="minus"></span>
Table:
<table class="table table-bordered table-striped" style="margin-bottom:0px;" id="myTable">
<tr>
<td>Customer Master #</td>
</tr>
<tr>
<td><input type="text" class="form-control" ></td>
</tr>
</table>
JS:
$(document).ready(function(){
$("#addrow").on("click", "span#add", function(){
var tablerow = '<tr><td><input type="text" class="form-control" ></td></tr>'
$("#myTable tr:last").after(tablerow);
})
$("#addrow").on("click", "span#minus", function(){
$('#myTable tr:last').remove();
} )
});
Not sure 100% you want changed with your code, but here is a fiddle which adds or removes - but will not remove the first row (won't eat the whole table).
http://jsfiddle.net/HR5se/
$('#myTable tr .form-control').size()
Will give you how many data (input) rows there are. In this fiddle, I check to see if there's greater than one data row, and if not, the remove doesn't happen.
Note: I turned your glyphs into "+" and "-" text so I could see them here.
See if changing the onclick event to mouseup has any effect. I had a similar problem a while back.
I added an if statement to only allow a row to be taken out if the table has 3 or more rows. This preserves the last two rows that I always want to be on the page.
if ($('#myTable tr').length > 2)
This seemed to solve the problem.
Full code:
$("#addrow").on("click", "span#minus", function(){
if ($('#myTable tr').length > 2) {
$('#myTable tr:last').remove();
};
} )

Categories

Resources