My end goal here is to take a button with a unique id from the index. Based off of the id is clicked (i.e. Which button I click) it deletes that corresponding table row. For example if I hit a delete button with an id of 1..then I want to delete the 1st table row within that table. I am having trouble understanding how I would do this.
Here is my code.
count = ["<TR>", "<TR>", "<TR>", "<TR>"]
$.each(count, function(index,value) {
index++;
$("#deletingRows table").append("<tr><td class='deleteRow' style='font-weight: bold;'>" + 'Row Number: ' + "<input type='text' name='rowNumber' id='rowNumber' style='margin-left: 45px;' value=" + index + ">" + "</input>" + "<input type='button' id='" + index + ' + "name='delete' value='Delete This Row'></input>" + "</td></tr>");
});
You can simplify this to :-
Give class delete to your button.
$('.delete').click(function(){
$(this).closest('tr').remove(); // closest('tr') will get you its parent tr and call .remove() to remove it.
});
or just use the name itself.
$('input[name=delete]').click(function(){
$(this).closest('tr').remove(); // closest('tr') will get you its parent tr and call .remove() to remove it.
});
See .closest()
Remember to put the click handler under document.ready.
Related
I'm trying to make dynamic table with javascript that elements can be dynamically added and removed with it.
Now, the remove function doesn't work probably.
I've tried .parent().parent().remove();
.parents("tr").remove();
.closest("tr").remove();
but they don't work.
The code to append to table :
$("table tbody").append("<tr><input type='hidden' name='label[]' value='" + $(".inputTitle").val() + "' /><input type='hidden' name='htmlText[]' value=\"" + html + "\" /><td>" + html + "</td><td>" + $(".inputTitle").val() + "</td><td>" + typeName + " ( " + crArabic + " )</td><td><a class='btn btn-danger deleteRow'><i class='fa fa-fw fa-times' aria-hidden='true'></i></a></td></tr>");
The Removal Code :
$("table tbody tr").on("click", ".deleteRow", function () {
$(this).parent().parent().remove();
});
The expected results to this is to add and remove table rows dynamically. However, the removing event isn't working.
You may have to read this SO answer Difference between $(document).on(“click”, “selector”, function …); and $(“selector”).on(“click”, function …) and change your code to:
$(document).on("click", ".deleteRow", function () { $(this).parent().parent().remove(); });
I've created a table using an AJAX request to the database of items in our inventory displaying a picture/part name/price/stock remaining. When the table displays I would like to be able to click on any part of one of the rows and have it link to the item page associated with that item but it won't work.
I've tried the on.click with a static table written right into the html and it worked fine. Also if I direct the on.click script to just the table id instead of the table id and tr i can make the entire table clickable to the first row's href. So it appears that since the tr doesn't really exist in the html the javascript won't find it. Is there a way to get the script to recognize each 's href attribute?
HTML CODE + on.click script:
<html>
<body>
<table id="ctable">
<tbody id="tbody1" class="tbody1">
</tbody>
</table>
<script>
$('#ctable tr').click(function() {
var href = $(this).find("a").attr("href");
if(href) {
window.location = href;
}
});
</script>
</body>
</html>
.JS File CODE that creates table from .php file/mysql database
document.addEventListener('DOMContentLoaded', function() {
$.post('test.php', function(data) {
$("#tbody1").empty();
$.each(JSON.parse(data), function (index, value){
var eachrow = "<tr>" +
"<td class=\"image\">" + '<img src="images/thumbs/' +
value.image + '">' + "</td>" +
"<td>" + '<a href="' + value.link + '">' + value.part + "
</td>" +
"<td>" + value.price + "</td>"
"<td>" + value.stock + "</td>"
"</tr>";
$('#tbody1').append(eachrow);
});
});
}, false);
If you are dynamically adding rows, you need to either restructure your click event to listen from the context of the parent as in:
$("#tbody1").on("click", "tr", function(e) {
});
Assuming #tbody1 is a good place to start since you probably don't want the header row to be clickable. Or, every time you dynamically add rows, since the code is rebuilding the table, you can reattach the click event handlers:
$("#tbody1").empty();
$.each(JSON.parse(data), function (index, value){
var eachrow = "..
$('#tbody1').append(eachrow);
});
// or .on("click", function() { })
$("#tbody1 tr").click(function() { });
If you attach click handler via on, it would be good to then do an off as in:
$("#tbody1").off("click", "tr");
To remove the existing click handlers.
I have a web page that is a dynamic form. It allows users to specify any number of Attributes to devices. These attributes can be select option lists. When the user selects this, they are presented with a button to add options.
My problem is that I need to know how many options there are for each attribute. I have tried using var counter=$('.class-name').next().val(); to try and count them alert(counter); to see if it works. But all I get is an alert of undefined so the var counter is not being initalised.
I need to know the number of options for each select list to be able to group them together and know which options go with a particular attribute. I cannot think of a way to do this through JS or PHP. I can get the options posted in the php but I can't identify what options go with each attribute.
Here is a fiddle!
Here is the code to get the lengths for each of the respective options.
$('.tattribute option:selected[value="text"]').length
$('.tattribute option:selected[value="checkbox"]').length
$('.tattribute option:selected[value="select-list"]').length
$('.tattribute option:selected[value="notes"]').length
Fiddle
Here is a fiddle with a hidden field added to keep track of the options count. Every time an option is added or removed the value of the hidden field is incremented or decremented. The changes are in the code below
var template="<div class=\"new-attribute\">"
+ "<h3>New Attribute</h3>"
+ "<label for=\"attributeName[]"+"\">Name:</label>"
+ "<input class=\"attribute\" type=\"text\" name=\"attributeName[]"+"\">"
+ "<input class=\"attribute_count\" type=\"hidden\" name=\"attributeCount[]"+"\">"
+ "<label for=\"attributeType[]"+"\">Type:</label>"
+ "<select class=\"tattribute\" name=\"attributeType[]"+"\">"
+ "<option value=\"text\" selected>Text</option>"
+ "<option value=\"checkbox\">Checkbox</option>"
+ "<option value=\"select-list\">Select Option List</option>"
+ "<option value=\"notes\">Notes</option>"
+ "</select>"
+ "<div class=\"option\"></div>"
+ "<button type=\"button\" class=\"remove\">Delete</button>"
+ "</div>";
And
//Add action
$("#attributes").on('click', '.btn', function () {
add = "<div class=\"op\"><label for=\"attributeOption[]" +"\">Name:</label>"
+ "<input class=\"option-input\" type=\"text\" name=\"attributeOption[]" + "\">"
+"<button type=\"button\" class=\"remove-option\">remove</button></div>";
$(this).after(add);
//COUNT NUMBER OF OPTIONS
$opt = $(this).closest('.option')
$opt.siblings('.attribute_count').val($opt.find('.op').length)
alert($opt.siblings('.attribute_count').val());
});
//Remove input
$("#attributes").on('click', '.remove-option', function () {
$(this).closest('.op').remove();
$opt = $(this).closest('.option')
$opt.siblings('attribute_count').val($opt.find('.op').length)
});
I am generating a dynamic table on click of a button as below -
$('.addRowButton').click(function () {
++counter;
var index=counter-1;
var newRowHtml =
'<tr>' +
'<td>' + counter +
'</td>' +
'<td><input name="b2bProductList[' + index+ '].productId" class="variant b2bTableInput" /></td>' +
'<td align="center"><span id="pvDetails" class="pvDetails"></span></td>' +
'<td><div class="img48" style="vertical-align: top;"><img src=""></td>'+
'<td><input name="b2bProductList[' + index + '].quantity" class="qty b2bTableInput"/></td>' +
'<td align="center"><span id="mrp" class="mrp"/></td>' +
'<td align="center"><input id="totalPrice" readonly="readonly" class="totalPrice b2bTableInput" type="text"></td>' +
'</tr>';
$('#poTable').append(newRowHtml);
But I want to handle a particular column my self - kind of override it. I have to display an image and have to use some attributes in this column it which I can not put in the above code. How should I override it. If I am going to declare any tr or td in my table in the main <table></table> they are taking up extra row statically. Is there any particular way to handle a particular column while adding the rows dynamically?
EDIT - I have to set the source of the image, the source string of which I am fetching through an async call on the focusout of my Id textbox. Now can not set the source in the row generation time, so I will have to handle each column at a time giving src after I have fetched it. The column is mentioned in my code
'<td><div class="img48" style="vertical-align: top;"><img src=""></td>'+
Now I have to set the src. I hope this tells my problem clearly.
You could use
$('#myTable tr td::nth-child('+columnIndex+')')
if you know the index of the column or you could give that specific td a unique class
newRowHtml ='<tr>' + '<td class="someClass"></td> ... etc
and select that class:
$('.someClass').each(function(){
// Some other code
});
Alternatively you could add the rows like so:
var $row = $('<tr></tr>');
var $id = $('<td></td>').html(id);
var $someOtherfield = $('<td></td>').html(someOtherData);
$('#myTable').append($row.append($id).append($someOtherfield));
then use the variable $someOtherfield to access it and work on it.
$someOtherfield.find('img').attr('src' , yourSource);
The simplest to select the cells of a specific column, if you have no fancy colspan, is to use :nth-child() :
$('#mytable td:nth-child('+columnIndex+')')
var tds= $('#poTable').find("td:first");
will give you the first column.
and to iterate over the elements
tds.each(function(index){
//do your stuff here..
});
hope this helps..
I was using this:
$('#' + tableID + "tr:first td:first")
To get my first cell, but there is potential the first cell isn't what I want. The cell I'm looking for is the first cell in the first row that has the class 'canEdit'. Any idea how to go about doing that?
Just add the respective class to your selector, like this:
If the row has to have the respective class:
$('#' + tableID + " tr.canEdit:first td:first")
Or if the cell has to have the class:
$('#' + tableID + " tr:first td.canEdit:first")
Also note the added space before the "tr" in the selector.
So what you want is this from my understanding
$('#' + tableID + " tr:first td.canEdit:first")
// gets "first cell" in the "first row" that has class edit
Add your class to the selector.
$('#' + tableID + " tr.canEdit:first td:first")
Add a class to the tr. You should also limit to the tbody so it does not look in the thead or tfoot for the rows.
$('#' + tableID + " tbody tr.canEdit:first td:first")