Add a new row dynamically with jQuery
You can use closest
to the tr
and then just replace append
with after
.
$(".add").click(function() { $(this).closest('tr').after('<tr><td>newrow</td><td>newrow</td><td>newrow</td></tr>');});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="prices-table" border="1"> <tr> <td>1</td> <td>Title<span class="add"><font color="red">add+</font></span></td> <td>price</td> </tr> <tr> <td>1</td> <td>Title</td> <td>price</td> </tr></table>
Adding rows dynamically with jQuery
This will get you close, the add button has been removed out of the table so you might want to consider this...
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
return false;
});
});
</script>
HTML markup looks like this
<a id="add">+</a></td>
<table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td>Name</td>
</tr>
<tr class="person">
<td><input type="text" name="name" id="name" /></td>
</tr>
</tbody>
</table>
EDIT To empty a value of a textbox after insert..
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last #name').val('');
return false;
EDIT2 Couldn't help myself, to reset all dropdown lists in the inserted TR you can do this
$("#mytable tbody>tr:last").each(function() {this.reset();});
I will leave the rest to you!
Dynamically add table row number using jquery
There are lots of ways to do this. As I post this, I see 3 viable options already posted. Here is what I would suggest.
$(function() { function numberRows($t) { var c = 0; $t.find("tr").each(function(ind, el) { $(el).find("td:eq(0)").html(++c + "."); }); } $("#add-service-button").click(function(e) { e.preventDefault(); var $row = $("<tr>"); $row.append($("<td>")); $row.append($("<td>").html($("#add-service").val())); $row.append($("<td>").html("<a class='del-service' href='#' title='Click to remove this entry'>X</a>")); $row.appendTo($("#service-table tbody")); numberRows($("#service-table")); }); $("#form-entry form").submit(function(e) { e.preventDefault(); $("#add-service-button").trigger("click"); }); $("#service-table").on("click", ".del-service", function(e) { e.preventDefault(); var $row = $(this).parent().parent(); var retResult = confirm("Are you sure you wish to remove this entry?"); if (retResult) { $row.remove(); numberRows($("#service-table")); } });});
.form-entry input { border: 1px solid #ccc; width: 75%; line-height: 2em; padding-left: 1em;}
.form-entry button { border: 0; background-color: #5AD0A1; color: #fff; cursor: pointer; padding: .6em 1.25em;}
.table-wrapper { font-family: Arial, sans-serif;}
.table-wrapper table td { border-bottom: 1px dashed #ccc; padding: 1em .2em;}
.table-wrapper table tr:last-child td { border-bottom: 0;}
.table-wrapper table td:first-child { color: #ccc; width: 2em;}
.table-wrapper table td:last-child a { color: #F00; text-decoration: none;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="form-entry"> <form> <input type="text" id="add-service" placeholder="Enter your service name here..." /> <button type="submit" id="add-service-button">Add</button> </form></div><div class="table-wrapper"> <table id="service-table" width="100%"> <tbody> </tbody> </table></div>
Dynamically add row with jQuery
You have to listen to the changes made in the element. You can try with MutationObserver
$(document).ready(function() { var counter = 0;
$("#addrow").on("click", function() { var newRow = $("<tr>"); var cols = "";
cols += '<td><input type="text" disabled value="123123123" class="form-control" name="name' + counter + '"/></td>'; cols += '<td><input type="text" disabled value="Sekop" class="form-control" name="mail' + counter + '"/></td>';
cols += '<td><input type="button" class="ibtnDel btn btn-md btn-danger " value="Delete"></td>'; newRow.append(cols); $("table.order-list").append(newRow); counter++; });
$("table.order-list").on("click", ".ibtnDel", function(event) { $(this).closest("tr").remove(); counter -= 1 });});
function calculateRow(row) { var price = +row.find('input[name^="price"]').val();}
function calculateGrandTotal() { var grandTotal = 0; $("table.order-list").find('input[name^="price"]').each(function() { grandTotal += +$(this).val(); }); $("#grandtotal").text(grandTotal.toFixed(2));}
// Listen to the changes in the header element and add rowvar target = document.querySelector('#myHeader');
setTimeout(function() { target.textContent = "New Barcode: XXXXXXXXX"; // change text after 2 seconds}, 2000)
var observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { $("#addrow").trigger("click"); // trigger the click event to add row if the header text is changed });});
var config = { attributes: true, childList: true, characterData: true};
observer.observe(target, config);
// otherwiseobserver.disconnect();observer.observe(target, config);
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"><script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<div class="container" align="top" style="margin-top: 0px;"> <h1 align="center" id="myHeader">Barcode: 123123123</h1> <table id="myTable" class=" table order-list"> <thead> <tr> <td>Barcode</td> <td>Item</td> </tr> </thead> <tbody> </tbody> <tfoot> <tr> <td colspan="7" style="text-align: left;"> <div align="right"> <p style="color: black;margin-right: 90px;">9.999.999</p> </div> <input type="button" class="btn btn-lg btn-block " id="addrow" value="Add Row" style="border-color: black;" /> </td> </tr> <tr> </tr> </tfoot> </table></div>
Add and Delete Rows Dynamically using jQuery
First of you are trying to append a invalid string. Your string should not have breaks between them (you can escape them using \
), instead have your string within one line. And use single quotes to surround the entire string and double quotes around other HTML attributes or you can have it the other way around.
Something like this:
var text= "<tr><td><input type='text'' class='index_txtBox'/></td>"
+"<td><input type='checkbox' class='check_box'/></td>"
+"<td><input type='text' class='txt_Box'/></td>"
+"<td><select><option></option></select></td></tr>";
Now, for the add button:
$(document).on('click', '#add_row', function(){
$('#test').append(text) //append the var defined
});
And then the delete button, delete the rows that are checked:
$(document).on('click', '#del_row', function(){
if(!$.trim($('#test').html()).length){ // If empty, do a alert
alert ("Now table is empty")
}else{
$('#test').children('tr').find('input[type=checkbox]:checked').each(function () { // look for the checked input
$(this).closest('tr').remove(); // remove the entire row closest to it
});
}
});
Here is a Demo.
Unable to add row dynamically to Jquery datatable
I created a little example with a little repository of mine, hoping it helps you solve your issue:
var table = $('#example').DataTable({
"bLengthChange": false,
//searching: false,
pageLength: 3,
dom: 'tip'
});
$.fn.dataTable.ext.search.push(function( settings, data, dataIndex ) {
var filterCategory= $("#cato option:selected").text().toUpperCase();
var filterSubCategory= $("#subo option:selected").text().toUpperCase();
var subCategory = String(data[2]).toUpperCase();
var category = String(data[3]).toUpperCase();
//console.log(filterSubCategory);
if(filterSubCategory != "-SELECT SUBCATEGORY-") {
if ( filterCategory == category && filterSubCategory == subCategory)
return true;
}
else if(filterCategory != "-SELECT CATEGORY-") {
if ( filterCategory == category)
return true;
}
return false;
}
);
$('#cato').on('change', function() {
$('#subo').val("");
table.draw();
});
$('#subo').on('change', function() {
table.draw();
});
function getInfo() {
var $subCategory = $("#subo option:selected").text()
$.ajax({
type:'GET',
url: "https://my-json-server.typicode.com/SagnalracSO/repo/items?subcategory=" + $subCategory,
/*data:{
name:$('#name').val(),
desc:$('#desc').val(),
category:$("#catoo option:selected").text(),
,
'csrfmiddlewaretoken': '{{ csrf_token }}'
},*/
dataType: "json",
beforeSend: function(jqXHR, settings) {
if($subCategory.toUpperCase() == '-SELECT SUBCATEGORY-') {
alert('Select a SubCategory');
jqXHR.abort();
}
},
success: function(data) {
var item = data[0];
var jRow = $("<tr>").append("<td>" + item.id + "</td><td>" + item.product + "</td><td>" + item.subcategory + "</td><td>" + item.category + "</td>").append("</tr>");
table.row.add(jRow).draw();
}
});
}
<link href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
<select id="cato" class="form-control" >
<option value="" disabled selected="true">-Select Category-</option>
<option>Electronics</option>
<option>Sports</option>
</select>
<select id="subo" class="form-control">
<option value="" disabled selected="true">-Select Subcategory-</option>
<option>Laptop</option>
<option>Mobile</option>
</select>
<table id="example" class="table display">
<thead>
<tr>
<th>Id</th>
<th>Product</th>
<th>Subcategory</th>
<th>Category</th>
</tr>
</thead>
<tbody id="r">
<tr>
<td>1</td>
<td>Samsung</td>
<td>Mobile</td>
<td>Electronics</td>
</tr>
<tr>
<td>2</td>
<td>Racket</td>
<td>Tennis</td>
<td>Sports</td>
</tr>
<tr>
<td>3</td>
<td>Bat</td>
<td>Cricket</td>
<td>Sports</td>
</tr>
<tr>
<td>4</td>
<td>Dell</td>
<td>Laptop</td>
<td>Electronics</td>
</tr>
<tr>
<td>5</td>
<td>Iphone</td>
<td>Mobile</td>
<td>Electronics</td>
</tr>
<tr>
<td>6</td>
<td>Soccer Ball</td>
<td>Soccer</td>
<td>Sports</td>
</tr>
</tbody>
</table>
<br><br>
<input type="button" value="ADD ROWS" onClick="getInfo()" />
Add and remove row dynamically from jquery from given content
Here is the modified code:
$(document).ready(function() {
$("#button").click(function(e){
e.preventDefault();
var name = $('#name').val();
var gender = $('input:radio[name=sex]:checked').val();
var resident= $('input:checkbox:checked').val();
var education = $("#selectbox").val();
var content = '<td>' + name + '</td>' +
'<td>' + gender + '</td>' +
'<td>' + resident + '</td>' +
'<td>' + education + '</td>' +
'<td><button class="edit-row">Edit</button><button class="delete-row">Delete</button></td>';
if ($(this).hasClass('save-edit')) {
$('.editing').html(content);
$("#button").removeClass('save-edit').val('Submit');
} else {
var rowContent = '<tr class="employee-row">' + content + '</tr>';
$('#empinfo').append(rowContent);
}
});
$('body').on('click', '.edit-row', function (e) {
$('.editing').removeClass('editing');
$(this).closest('.employee-row').addClass('editing');
$("#button").addClass('save-edit').val('Save');
});
$('body').on('click', '.delete-row', function (e) {
$(this).closest('.employee-row').remove();
});
});
and jsfiddle:
https://jsfiddle.net/s6wty7vv/2/
Related Topics
Webpack File-Loader Outputs [Object Module]
Uncaught Typeerror: Cannot Read Property 'Top' of Undefined
What's the Difference Between Putting Script in Head and Body
Embed an External Page Without an Iframe
How to Create a Responsive Image That Also Scales Up in Bootstrap 3
React: How to Load and Render External HTML File
<Script> Tag VS <Script Type = 'Text/Javascript'> Tag
Css3-Animate Elements If Visible in Viewport (Page Scroll)
Removing Page Title and Date When Printing Web Page (With CSS)
How to Convert HTML Table to Excel with Multiple Sheet
Accessing Localstorage from a Webworker
How to Abort Image <Img> Load Requests Without Using Window.Stop()
Bootstrap V2 Dropdown Navigation Not Working on Mobile Browsers
How to Detect Supported Video Formats for the HTML5 Video Tag
How to Rotate a Single Object on an HTML 5 Canvas
How to Store a Byte Array in JavaScript
How to Test If a Variable Does Not Equal Either of Two Values