Insert Table Row and Remove button from original row - javascript

I've got a form with a table with originally 1 row of input fields. Users can click the "New Row" button to get another row, with empty input fields. This leaves with me multiple copies of the "New Row" button for every Row - I would like to remove all but the most recently created "New Row" button (i.e. the one in the last row of input fields).
I've setup a sample JSFiddle at:
http://jsfiddle.net/fmdataweb/vRe9v/2/
Is there something I can add to the existing js that will delete the button that was clicked whilst leaving the newly created button in the new row? Here's the Javascript:
var table = $( '#nextYear' )[0];
$( table ).delegate( '#button2', 'click', function () {
var thisRow = $( this ).closest( 'tr' )[0];
$( thisRow ).clone().insertAfter( thisRow ).find( 'input:text' ).val( '' );
});
​

Use $(this).remove(); jQuery $(this) in the event of control represents the control whom event is fired on. You can use remove() method that will remove the button being click from dom
Live Demo
var table = $('#nextYear')[0];
$(table).delegate('#button2', 'click', function() {
var thisRow = $(this).closest('tr')[0];
$(thisRow).clone().insertAfter(thisRow).find('input:text').val('');
$(this).remove();
});​

You can use jQuery remove() which removes the set of matched elements from the DOM.
In your case as you are within the button click event, this is what references the button object in the DOM.
Turn this into a jQuery object and call remove() on it like this:
$(this).remove();
Complete new code:
var table = $('#nextYear')[0];
$(table).delegate('#button2', 'click', function() {
var thisRow = $(this).closest('tr')[0];
$(thisRow).clone().insertAfter(thisRow).find('input:text').val('');
$(this).remove(); // remove button that was clicked
});​
See DEMO

Try this: DEMO: http://jsfiddle.net/xRQs8/2/
It can be done using single button :+
<table id="dataTable" cellspacing="0" cellpadding="0" border="0" width="100%">
<tr>
<td>
<input type="Button" value="Add More" name="AddMore" class="AddOption" />
</td>
</tr>
</table>

Related

Disable click fot td for particular column using Jquery

I have tried to use Jquery to click a table row to go to a new page. But my last column has a button. For which clicking on the edge takes it to a new page. Anyway to disable the td onclick for that column. I tried using onclick='event.stopPropagation();return false;' but that would disable the button too.
My Jquery code below.
$(".myTable").on("click", "td", function(){
var issueid = $(this).closest('tr').find("td:eq(2) input").val();
window.location = 'viewminissues.jsp?issue_id='+issueid;
});
This can be handled in two ways:
Try adding event.preventDefault() along with event.stopPropagation().
Add a disabled class on the td element manually and then handle further scenarios with hasClass('disabled') check.
The issue is because the click event from the button propagates up the DOM to the tr which then transfers the page.
To fix this you could call stopPropagation() within the button event handler:
$(".myTable").on("click", "td", function() {
var issueid = $(this).closest('tr').data('issue');
console.log('Transferring to: viewminissues.jsp?issue_id=' + issueid);
//window.location.assign('viewminissues.jsp?issue_id=' + issueid);
});
$('.myTable').on('click', 'button', function(e) {
e.stopPropagation();
console.log('Perform button action...');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="myTable">
<tr data-issue="1">
<td>Foo bar</td>
<td><button>Edit</button></td>
</tr>
<tr data-issue="2">
<td>Lorem ipsum</td>
<td><button>Edit</button></td>
</tr>
</table>
You can exclude the last <td> from the click() event using :not(:last) like this:
$(".myTable").on("click", "td:not(:last)", function() {
var issueid = $(this).closest('tr').find("td:eq(2) input").val();
window.location = 'viewminissues.jsp?issue_id=' + issueid;
});

Alert toggles every time when the input is changed

I have input and it toggles a function if it's been changed. I also have table that is created dynamically. And each row in table has an addButton. So, the problem is that this alert toggles so many times so I change the input, but I need to toggle it only once. How to deal with it?
$('.inputsearchform').bind('input', function() {
var addButton = $(".fa.fa-plus");
addButton.click(function() {
alert("test");
});
});
I don't need to add click event to this button, but I need to get onclick() event from it. But this code is only working way, that I found. By the way, I need to get this event only if button is clicked, not every time that I change input.
Question How to check onclick event on button, that appears dynmically, when the input changes?
I tried to add onclick event <i class="fa fa-plus" onclick="addButtonF()">
and in js file: function addButtonF(){
alert("test");
}
but I have an error addButtonF is not defined.
A start would be to define click outside of input handler to prevent multiple click handler calls at each click of addButton
So, the problem is that this alert toggles so many times so I change
the input, but I need to toggle it only once.
Not clear from Question which element needs to be toggled once, or which function should only be called once ?
addButton appears only if I write something in input. I need to use
alert only if I click on this button, not every time that I change
input.
Use event delegation to attach event to dynamically created elements having className .fa.fa-plus
$(".inputsearchform").bind("input", function() {
// create dynamic element
$("<table class='fa fa-plus'>")
.html("<tr><td>"
+ $(".fa.fa-plus").length
+ "</td></tr>"
).appendTo("body");
});
$(document).on("click", ".fa.fa-plus", function() {
alert("test");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" class="inputsearchform">
Substitute className for class which does not set className of element; use latest version of jQuery
$(".inputsearchform").bind("input", function() {
var div = document.getElementById("div");
var table = document.createElement("table");
div.appendChild(table);
var tr = document.createElement("tr");
table.appendChild(tr);
var td = tr.insertCell(0);
td.innerHTML = "test";
td.className = "try"
});
$(document).on("click", ".try", function() {
alert("test");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" class="inputsearchform">
<div id="div"></div>
jsfiddle https://jsfiddle.net/1x8ja6qe/2/

how to add onclick events to dynamically generated buttons and show /hide the table

I have many buttons generating dynamically based on end user request
$out='<input class="show_hide" type="button" id="'.$platform_name.'" value="'.$platform_name.'"/>';
the same variable name tables also coming dynamically
$out.='<table id="'.$platform_name.'" > </table>
if suppose button
<input class="show_hide" type="button" id="button1'" value="button1"/>
<table id="button1" > </table>
how to get the number of button names/id, and based on button name/id finding table and show/ hide the table. Please help me. i am fresher in php
when it comes to dynamic binding, go for delegates
$( "body" ).on( "click", ".show_hide", function() {
$( this ).next().toggle();
});
OR you can provide selector in sibling selection
$( "body" ).on( "click", ".show_hide", function() {
$( this ).next("#table1").toggle();
});
this code will hide/show the next sibling(in your case a table) on button click with class show_hide
The id should be unique in your HTML. E.g.
<input class="show_hide" type="button" id="button1'" value="button1"/>
<table id="table1"></table>
Then, you can 'choose' either the button or the table with jQuery using:
$('#button1')
$('#table1')
E.g.
for (var i = 1; i <= numberOfTables; i++) {
$('#button' + i).click(function() {
$('#table' + i).hide();
});
}
If you want to add event handler dynamically to element, ensure that you can have id for that element, you can do using plain javascript,
elemm.onclick = function() { alert('blah'); };
where elemm = document.getElementById("button1")
try like this using delegate:
all button click event:
$(document).on( ".show_hide", "click", function() {
//all button click
})
for the table use wildcart:
$(document).on( "[id^=table]", "click", function() {
//all table click
})
you also use wildcart for button also like this:
$(document).on( "[id^=button]", "click", function() {
//all table click
})
As others have said, id's must be unique. Your button and table can't have the same id. But you can use the value of your button to find the associated table:
$out='<input class="show_hide" type="button" value="'.$platform_name.'"/>';
Since the buttons are dynamic, you don't know the ids of all of the buttons, but you can use the jQuery class selector to find all buttons with the show_hide class and apply a function to the click event:
$("input.show_hide").on('click', function () {
// get the id of the table associated with the button
var tableId = $(this).val(),
// toggle your table between hide and shown
$("#" + tableId).toggle();
});
If your tables can be added dynamically AFTER the page loads, you will have to use a delegate for defining the click event:
$(document).on( ".show_hide", "click", function() {
.. same code goes here
});

Javascript/JQuery to add and delete table row by Id

I am trying to add and delete rows (by Id) to my table dynamically. The add button works fine but I am not sure why the delete button doesn't work (it's either deletes the last row or doesn't work). Any suggestion please?
Here is my table:
<table class="customFiltersTable" id="customFiltersTable">
<tbody>
</tbody>
</table>
The Javascript add button has this code inside:
filtersRow = filtersRow + 1;
var fType1 = $('<tr class="rowTableFilters" id="rowFilters'+filtersRow+'" name="rowFilters'+filtersRow+'"><td class="colFilters" id="colFilters'+column1+'" name="colFilters'+column1+'" width="480px" align="center"></td><td class="colFilters" id="colFilters'+column2+'" name="colFilters'+column2+'" width="480px" align="center"></td><td class="delButton" id="delButton" name="delButton" width="40px" align="center"><button type="button" class="btn btn-link" id="deleteFilter'+filtersRow+'" name="deleteFilter'+filtersRow+'" style="float: right;">Del</button></td></tr>');
$("#customFiltersTable").append(fType1).promise().done(function () {
$("#deleteFilter" + filtersRow).click(function(){
var row = document.getElementById("rowFilters"+filtersRow);
row.parentNode.removeChild(row);
});
});
Thanks!
Acquaint yourself with jQuery's event delegation, https://learn.jquery.com/events/event-delegation/. You'll learn that you can avoid attaching the delete click listener to every row you add, and instead attach that listener once to the table element:
$('#customFiltersTable').on('click', 'button', function () {
$(this).closest('tr').remove();
});
You're incrementing filtersRow; however your click function only gets evaluated at the time you press the button. In other words, this code:
function(){
var row = document.getElementById("rowFilters"+filtersRow);
row.parentNode.removeChild(row);
}
is executed on click and will run with whatever value of filtersRow you last incremented. You'll always be removing the last row.
Perhaps something like:
function () {
$(this).closest('tr').remove();
}
Sorry, this is compiled in my head.
To add row:
var tmp = '<tr id="4_r"><td>row4</td></tr>';
$('#myTable tbody').append(tmp);
To delete row have id="4_r":
var iddel = "4_r";
$('#myTable').closest('table').find('tbody > tr')
.each(function(){
var idr = this.id;
if(idr == iddel){
$(this).remove();
}
});

jQuery - Click event on <tr> elements with in a table and getting <td> element values

I have the following HTML in a JSP file:
<div class="custList">
<table class="dataGrid">
<c:forEach var="cust" items="${custList}">
<tr>
<td>${cust.number}</td>
<td>${cust.description}</td>
<td>${cust.type}</td>
<td>${cust.status}</td>
</tr>
</c:forEach>
</table>
</div>
I need to be able to trigger a 'click' event on each of the dynamically created <tr> tags and also be able to access the values of the <td> tags (of the clicked <tr>) from within the JavaScript function. I have this function already, but sadly it doesn't seem to be working.
$(document).ready(function() {
$("div.custList > table > tr").live('click', function() {
alert("You clicked my <tr>!");
//get <td> element values here!!??
});
});
Update (Jan 2016): jQuery.live is deprecated (as noted here:http://api.jquery.com/live/)
As of jQuery 1.7, the .live() method is deprecated. Use .on() to
attach event handlers.
Unless otherwise definied (<tfoot>, <thead>), browsers put <tr> implicitly in a <tbody>.
You need to put a > tbody in between > table and > tr:
$("div.custList > table > tbody > tr")
Alternatively, you can also be less strict in selecting the rows (the > denotes the immediate child):
$("div.custList table tr")
That said, you can get the immediate <td> children there by $(this).children('td').
Try jQuery's delegate() function, like so:
$(document).ready(function(){
$("div.custList table").delegate('tr', 'click', function() {
alert("You clicked my <tr>!");
//get <td> element values here!!??
});
});
A delegate works in the same way as live() except that live() cannot be applied to chained items, whereas delegate() allows you to specify an element within an element to act on.
This work for me!
$(document).ready(function() {
$(document).on("click", "#tableId tbody tr", function() {
//some think
});
});
Since TR elements wrap the TD elements, what you're actually clicking is the TD (it then bubbles up to the TR) so you can simplify your selector. Getting the values is easier this way too, the clicked TD is this, the TR that wraps it is this.parent
Change your javascript code to the following:
$(document).ready(function() {
$(".dataGrid td").click(function() {
alert("You clicked my <td>!" + $(this).html() +
"My TR is:" + $(this).parent("tr").html());
//get <td> element values here!!??
});
});​
$("body").on("click", "#tableid tr", function () {
debugger
alert($(this).text());
});
$("body").on("click", "#tableid td", function () {
debugger
alert($(this).text());
});
$(this).find('td') will give you an array of td's in the tr.
<script>
jQuery(document).ready(function() {
jQuery("tr").click(function(){
alert("Click! "+ jQuery(this).find('td').html());
});
});
</script>

Categories