I have table tag in cshtml page and append tr and td via ajax,now i dont know how to say delete row when i click on it,furthermore i dont know how to get value of inputs in each row.
/// <reference path="jquery-2.2.4.js"/>
$(document).ready(function () {
$.ajax({
type: "GET",
url: "api/ProductsApi/GetProducts",
success: function (Products) {
debugger;
let item0 = '<tr>' +
'<th>d</th>' +
'<th>d</th>' +
'<th>d</th>' +
'<th>d</th>' +
'<th>d</th>' +
'</tr>';
$("#AdminProductList").append(item0);
for (var i = 0; i < Products.length; i++) {
var d = Products[i].split("/");
let item = '<tr >' +
'<td><img src="/locker/' + d[0] + ' "alt="gnjh " style="width:70px;height:70px" /></td>' +
'<td>'+d[3]+'</td>' +
'<td>'+d[2]+'</td>'+
'<td>' + d[1] + '</td>' +
'<input id="AdminProductId'+i+'" type="hidden" value="'+d[5]+'" />'+
'<td id="'+i+'">' +
'<button data-toggle="tooltip" value="'+d[5]+'" class="pd-setting-ed eachEdit"><i class="fa fa-pencil-square-o" aria-hidden="true"></i><input type="hidden" value="' + d[5] +'"/></button>' +
'<button data-toggle="tooltip" title="Trash" class="pd-setting-ed eachTrash"><i class="fa fa-trash-o" aria-hidden="true"></i></button>' +
'</td>' +
'</tr>';
$("#AdminProductList").append(item);
}
},
error: function (f) {
debugger;
alert("nashod");
}
});
})
<div id="ListPage" style="display:none" class="product-status mg-tb-15">
<div class="container-fluid">
<div class="row">
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="product-status-wrap" style="direction:rtl;">
<h4>f</h4>
<button style=" border: 0;width: 270px;padding: 10px;-webkit-border-radius: 5px;-moz-border-radius: 5px;border-radius: 5px;display: block;text-decoration: none;text-align: center;font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;font-size: 1.2em;color: #FFF;background: #bc3737;-webkit-box-shadow: 0 3px 1px #950d0d;-moz-box-shadow: 0 3px 1px #950d0d;box-shadow: 0 3px 1px #950d0d;" class="add-product" id="Edit"> افزودن محصول</button>
<table id="AdminProductList" style="direction:rtl;">
</table>
</div>
</div>
</div>
</div>
</div>
i dont kow how to say when i click,by id................................
...............................................................................
.........................................................
..................................................
........................................................................
......................................................................
.
.......................
I think you should add an event listener to the table rows in order to delete them:
$(document).on('click', '#AdminProductList>tr', function(){
$(this).remove()
});
And if you want to get input values, actually there are a lot of ways to do it. If you want to get all the input values, you can traverse over them like this:
function getInputValues(){
$('tr input').each(function(){
console.log($(this).val());
});
}
Try like this:
$.ajax({
type:'POST',
url:'delete.php',
data:{del_id:del_id},
success: function(data){
if(data=="YES"){
$ele.fadeOut().remove();
}else{
alert("can't delete the row")
}
}
})
})
$('button').click(function(){
var tr = $(this).closest('tr');
var inputs = tr.find('input');
alert($(inputs[0]).val());
alert($(inputs[1]).val());
tr.remove();
})
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" /></td>
<td>Hidden value here<input type="hidden" value="test hidden" /></td>
<td><button>Remove</button></td>
</tr>
</table>
You can use this script
$('button').click(function(){
$(this).closest('tr').remove();
})
or write click method
<button click="remove(this)" data-toggle="tooltip" title="Trash" class="pd-setting-ed eachTrash"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
function remove(item){
$(item).closest('tr').remove();
}
Updated: i create a demo for get input value.
var inputs = tr.find('input');
alert($(inputs[0]).val());
alert($(inputs[1]).val());
You need to add an on click event handler for the delete button and then delete that specific row.
I have edited your code to add the event listener and also delete the element.
/// <reference path="jquery-2.2.4.js"/>
$(document).ready(function () {
window.deleteTableRow = function (selector) { $('tr'+selector).remove(); }
$.ajax({
type: "GET",
url: "api/ProductsApi/GetProducts",
success: function (Products) {
debugger;
let item0 = '<tr>' +
'<th>d</th>' +
'<th>d</th>' +
'<th>d</th>' +
'<th>d</th>' +
'<th>d</th>' +
'</tr>';
$("#AdminProductList").append(item0);
for (var i = 0; i < Products.length; i++) {
var d = Products[i].split("/");
let item = '<tr class="data-delete-index-'+ i +'">' +
'<td><img src="/locker/' + d[0] + ' "alt="gnjh " style="width:70px;height:70px" /></td>' +
'<td>'+d[3]+'</td>' +
'<td>'+d[2]+'</td>'+
'<td>' + d[1] + '</td>' +
'<input id="AdminProductId'+i+'" type="hidden" value="'+d[5]+'" />'+
'<td id="'+i+'">' +
'<button data-toggle="tooltip" value="'+d[5]+'" class="pd-setting-ed eachEdit"><i class="fa fa-pencil-square-o" aria-hidden="true"></i><input type="hidden" value="' + d[5] +'"/></button>' +
'<button onclick="deleteTableRow(\'.data-delete-index-'+ i +'\')" data-toggle="tooltip" title="Trash" class="pd-setting-ed eachTrash"><i class="fa fa-trash-o" aria-hidden="true"></i></button>' +
'</td>' +
'</tr>';
$("#AdminProductList").append(item);
}
},
error: function (f) {
debugger;
alert("nashod");
}
});
})
Related
I have a problem in how to add checkboxes dynamically to the javascript code. I have different scenario. I am getting data through ajax So I need to add table thead in the javascript rather than the html. But now I want to add Checkboxes to my thead. Indeed I added them but I don't know how to check them all with one checkbox. I write also code for that to select all but thats only working when my thead is in the html. Below is my code and it will give you a clear view. Try to read it in the editor because its a more compicated :)
//Javascript
$(document).ready(function() {
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
$('select[name="class_id"]').on('change', function() {
var classID = $(this).val();
if (classID) {
$.ajax({
url: '/attendance/ajax/' + classID,
type: "GET",
dataType: "json",
success: function(data) {
var markup = '';
markup += '<tr><th style="width: 2%" class="align-middle text-center"><input type="checkbox" id="options"></th><th style="width: 2%" class="align-middle text-center">#</th> <th style="width: 15%" class="text-center">Student ID<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Student Name<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Attendance<input type="text" class="form-control" disabled></th> <th style="width: 15%" class="text-center">Date<input type="text" class="form-control" disabled></th> <th style="width: 15%;" class="align-middle text-center">Actions</th> <tr>';
$.each(data, function(key, value) {
markup += '<tr> <td><input class="checkBoxes" type="checkbox" name="checkBoxArray[]"></td> <td><input type="hidden" value="' + value.id + '" name="id[]">' + value.id + '</td> <td><input type="hidden" value="' + value.student_id + '" name="student_id[]">' + value.student_id + '</td> <td><input type="hidden" value="' + value.first_name + '" name="first_name[]"><input type="hidden" value="' + value.last_name + '" name="last_name[]">' + value.first_name + ' ' + value.last_name + '<td><input type="hidden" value="' + value.attendance + '" name="attendance[]">' + value.attendance + '</td>' + '<td><input type="hidden" value="' + value.created_at + '" name="created_at[]">' + value.created_at + '</td>' + '<td style=" width=12%" class="text-center"> <a><button title="Edit" class="btn btn-outline-primary"><span class="fas fa-pencil-alt"></span></button></a> </td>' + '</td> <tr>';
});
$('table[id="studentsData"]').html(markup);
}
});
}
});
});
//For selecting all checkboxes
$(document).ready(function() {
$('#options').click(function() {
if (this.checked) {
$('.checkBoxes').each(function() {
this.checked = true;
});
} else {
$('.checkBoxes').each(function() {
this.checked = false;
});
}
});
});
The issue is the execution of event handlers on DOM elements.
The browser renders and executes code from top to bottom (in most cases).
This means that you execute $('#options').click() before you add all checkboxes via Ajax request.
Therefore you are trying to attach an event handler to elements which are not present at that moment of time.
To make it work, you have to add an event listener to the parent element
$('table[id="studentsData"]').on('click', '#options', function() {})
Source:
http://api.jquery.com/on/
The second argument is a selector you are going to target
In MVC5, I tried to add/remove rows with glyphicon. I want to pass the "rowcount" (Table Row Count) from jquery to "For Loop" (#for (int i = 0; i < rowCount; i++)) inside the .CSHTML.
Please refer the image which I tried to achieve.
Script:
<script>
$(function () {
$('.glyphicon-plus').click(function () {
var sds = $(this);
$(this).closest("tr").clone(true).appendTo('#ruleTable');
var **rowCount** = $('#ruleTable tr').length;
});
$('.glyphicon-remove').click(function () {
$(this).closest("tr").remove();
});
});
</script>
HTML.BeginForm :
#for (int i = 0; i < rowCount; i++){
<tr>
<td>
<span class="glyphicon glyphicon-plus" stye="color:lawngreen"></span>
<span class="glyphicon glyphicon-remove" style="color:red"></span>
</td>
<td> #Html.TextBox("[" + i + "].DepartmentCode") </td>
<td> #Html.TextBox("[" + i + "].DepartmentName")</td>
</tr>
}
Thanks...
Its Not Possible,Jquery is client side for loop in server side. so you can use One javascript or jquery function and use ajax to make this functionalities.
Thanks,
You can try like this
html
<div class="table-responsive" id="DivTable">
<table class="table table-bordered" id="tbl">
<thead>
<tr>
<td>Name</td>
<td>Age</td>
<td>DOB</td>
<td>Salary</td>
<td>Industry</td>
<td>Action</td>
</tr>
</thead>
<tbody id="dtEmployeeDetails">
</table>
</div>
javascript
function GetEmployeeDetails() {
var EmployeeArray = [];
$("#dtEmployeeDetails").empty();
$.ajax({
type: "POST",
url: '#Url.Action("GetEmployeeDetails", "Employee")',
dataType: 'json',
//data: JSON.stringify({ id: '2' }),
contentType: "application/json; charset=utf-8",
success: function (data) {
$.each(data, function (key, val) {
EmployeeArray[key] = '<tr>' +
'<td>' + val.Name + '</td>' +
'<td>' + val.DateofBirth + '</td>' +
'<td>' + val.Age + '</td>' +
'<td>' + Industry + '</td>' +
'<td>' + val.Salary + '</td>' +
'<td>' + '<a class="btn btn-success btn-xs" title="Edit" id="' + val.EmpID + '" onclick="EditEmployeeDetails(this.id);">' + '<span class="glyphicon glyphicon-pencil"></span></a> ' +
'<a class="btn btn-danger btn-xs" title="Delete" id="' + val.EmpID + '" onclick="DeleteEmployeeDetails(this.id);"><span class="glyphicon glyphicon-trash"></span></a></td></tr>';
});
$("#dtEmployeeDetails").html(EmployeeArray.join(""));
if (data.length == 0) {
$("#dtEmployeeDetails").append('<td colspan="6" class="text-center">No Record Found.</td>');
}
}
});
}
I am using Opencart 2.3.0.2 and I am trying to change the html of the order edit page to be in one page layout (By default is with bootstrap tabs).
It looks like it's loading the information for the next tab when you click the button on the previous page to continue.
And when I change it to one page it does not load the information on
document.ready but on click of the button.
I've got the following code:
$('#button-refresh').on('click', function() {
console.log('you've clicked button-refresh');
$.ajax({
url: '<?php echo $catalog; ?>index.php?route=api/cart/products&token=' + token + '&store_id=' + $('select[name=\'store_id\'] option:selected').val(),
dataType: 'json',
crossDomain: true,
success: function(json) {
$('.alert-danger, .text-danger').remove();
// Check for errors
if (json['error']) {
if (json['error']['warning']) {
$('#content > .container-fluid').prepend('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + json['error']['warning'] + ' <button type="button" class="close" data-dismiss="alert">×</button></div>');
}
if (json['error']['stock']) {
$('#content > .container-fluid').prepend('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + json['error']['stock'] + '</div>');
}
if (json['error']['minimum']) {
for (i in json['error']['minimum']) {
$('#content > .container-fluid').prepend('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + json['error']['minimum'][i] + ' <button type="button" class="close" data-dismiss="alert">×</button></div>');
}
}
}
var shipping = false;
html = '';
console.log(json['products'].length);
if (json['products'].length) {
for (i = 0; i < json['products'].length; i++) {
product = json['products'][i];
html += '<tr>';
html += ' <td class="text-left">' + product['name'] + ' ' + (!product['stock'] ? '<span class="text-danger">***</span>' : '') + '<br />';
html += ' <input type="hidden" name="product[' + i + '][product_id]" value="' + product['product_id'] + '" />';
if (product['option']) {
for (j = 0; j < product['option'].length; j++) {
option = product['option'][j];
html += ' - <small>' + option['name'] + ': ' + option['value'] + '</small><br />';
if (option['type'] == 'select' || option['type'] == 'radio' || option['type'] == 'image') {
html += '<input type="hidden" name="product[' + i + '][option][' + option['product_option_id'] + ']" value="' + option['product_option_value_id'] + '" />';
}
if (option['type'] == 'checkbox') {
html += '<input type="hidden" name="product[' + i + '][option][' + option['product_option_id'] + '][]" value="' + option['product_option_value_id'] + '" />';
}
if (option['type'] == 'text' || option['type'] == 'textarea' || option['type'] == 'file' || option['type'] == 'date' || option['type'] == 'datetime' || option['type'] == 'time') {
html += '<input type="hidden" name="product[' + i + '][option][' + option['product_option_id'] + ']" value="' + option['value'] + '" />';
}
}
}
html += '</td>';
html += ' <td class="text-left">' + product['model'] + '</td>';
html += ' <td class="text-right"><div class="input-group btn-block" style="max-width: 200px;"><input type="text" name="product[' + i + '][quantity]" value="' + product['quantity'] + '" class="form-control" /><span class="input-group-btn"><button type="button" data-toggle="tooltip" title="<?php echo $button_refresh; ?>" data-loading-text="<?php echo $text_loading; ?>" class="btn btn-primary"><i class="fa fa-refresh"></i></button></span></div></td>';
html += ' <td class="text-right">' + product['price'] + '</td>';
html += ' <td class="text-right">' + product['total'] + '</td>';
html += ' <td class="text-center" style="width: 3px;"><button type="button" value="' + product['cart_id'] + '" data-toggle="tooltip" title="<?php echo $button_remove; ?>" data-loading-text="<?php echo $text_loading; ?>" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></td>';
html += '</tr>';
if (product['shipping'] != 0) {
shipping = true;
}
}
}
if (!shipping) {
$('select[name=\'shipping_method\'] option').removeAttr('selected');
$('select[name=\'shipping_method\']').prop('disabled', true);
$('#button-shipping-method').prop('disabled', true);
} else {
$('select[name=\'shipping_method\']').prop('disabled', false);
$('#button-shipping-method').prop('disabled', false);
}
if (json['vouchers'].length) {
for (i in json['vouchers']) {
voucher = json['vouchers'][i];
html += '<tr>';
html += ' <td class="text-left">' + voucher['description'];
html += ' <input type="hidden" name="voucher[' + i + '][code]" value="' + voucher['code'] + '" />';
html += ' <input type="hidden" name="voucher[' + i + '][description]" value="' + voucher['description'] + '" />';
html += ' <input type="hidden" name="voucher[' + i + '][from_name]" value="' + voucher['from_name'] + '" />';
html += ' <input type="hidden" name="voucher[' + i + '][from_email]" value="' + voucher['from_email'] + '" />';
html += ' <input type="hidden" name="voucher[' + i + '][to_name]" value="' + voucher['to_name'] + '" />';
html += ' <input type="hidden" name="voucher[' + i + '][to_email]" value="' + voucher['to_email'] + '" />';
html += ' <input type="hidden" name="voucher[' + i + '][voucher_theme_id]" value="' + voucher['voucher_theme_id'] + '" />';
html += ' <input type="hidden" name="voucher[' + i + '][message]" value="' + voucher['message'] + '" />';
html += ' <input type="hidden" name="voucher[' + i + '][amount]" value="' + voucher['amount'] + '" />';
html += ' </td>';
html += ' <td class="text-left"></td>';
html += ' <td class="text-right">1</td>';
html += ' <td class="text-right">' + voucher['price'] + '</td>';
html += ' <td class="text-right">' + voucher['price'] + '</td>';
html += ' <td class="text-center" style="width: 3px;"><button type="button" value="' + voucher['code'] + '" data-toggle="tooltip" title="<?php echo $button_remove; ?>" data-loading-text="<?php echo $text_loading; ?>" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></td>';
html += '</tr>';
}
}
if (!json['products'].length && !json['vouchers'].length) {
html += '<tr>';
html += ' <td colspan="6" class="text-center"><?php echo $text_no_results; ?></td>';
html += '</tr>';
}
$('#cart').html(html);
// Totals
html = '';
if (json['products'].length) {
for (i = 0; i < json['products'].length; i++) {
product = json['products'][i];
html += '<tr>';
html += ' <td class="text-left">' + product['name'] + ' ' + (!product['stock'] ? '<span class="text-danger">***</span>' : '') + '<br />';
if (product['option']) {
for (j = 0; j < product['option'].length; j++) {
option = product['option'][j];
html += ' - <small>' + option['name'] + ': ' + option['value'] + '</small><br />';
}
}
html += ' </td>';
html += ' <td class="text-left">' + product['model'] + '</td>';
html += ' <td class="text-right">' + product['quantity'] + '</td>';
html += ' <td class="text-right">' + product['price'] + '</td>';
html += ' <td class="text-right">' + product['total'] + '</td>';
html += '</tr>';
}
}
if (json['vouchers'].length) {
for (i in json['vouchers']) {
voucher = json['vouchers'][i];
html += '<tr>';
html += ' <td class="text-left">' + voucher['description'] + '</td>';
html += ' <td class="text-left"></td>';
html += ' <td class="text-right">1</td>';
html += ' <td class="text-right">' + voucher['amount'] + '</td>';
html += ' <td class="text-right">' + voucher['amount'] + '</td>';
html += '</tr>';
}
}
if (json['totals'].length) {
for (i in json['totals']) {
total = json['totals'][i];
html += '<tr>';
html += ' <td class="text-right" colspan="4">' + total['title'] + ':</td>';
html += ' <td class="text-right">' + total['text'] + '</td>';
html += '</tr>';
}
}
if (!json['totals'].length && !json['products'].length && !json['vouchers'].length) {
html += '<tr>';
html += ' <td colspan="5" class="text-center"><?php echo $text_no_results; ?></td>';
html += '</tr>';
}
$('#total').html(html);
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
and I tried hacking it by simulating a click when the document load like this:
$(document).ready(function() {
$('#button-refresh').trigger('click');
});
the strange thing is that it works fine when I click the button in the browser, but it gives me error when I try to simulate the click with jquery. The errors is when I am trying to console.log the json['products']. It says:
Uncaught TypeError: Cannot read property 'length' of undefined
at Object.success (index.php?route=sale/order/edit&order_id=18&token=m0x3pTbrP0KbaBKSIQR4Jw4XndGGbrAS:1002)
at j (jquery-2.1.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-2.1.1.min.js:2)
at x (jquery-2.1.1.min.js:4)
at XMLHttpRequest. (jquery-2.1.1.min.js:4)
EDIT:
one more strange things is that the button does not have id="button-refresh" but it detects it somehow.
the button:
<button type="button" id="button-customer" data-loading-text="<?php echo $text_loading; ?>" class="btn btn-primary"><i class="fa fa-arrow-right"></i> <?php echo $button_continue; ?></button>
and when I tried
$(document).ready(function() {
$('#button-customer').trigger('click');
});
nothing happens.
try document.on click event like below.
$(document).ready(function() {
$(document).on('click', "#button-refresh", function () {
$(this).trigger('click');
});
});
I'm using bootstrap table library in my app that to render table with massive data and I need to open row in additional editable table. I found a lot of info in internet how to open row in model and put edited code to my app that to display row info inside div but cannot set it that to open it in editable table. I provide the plunker example.
Updated Cause I didn't get any work solution, I've tried to fix it by myself, so I know the solution isn't so good but for now it works for me. The question is still asking, how to edit field of new rendered table?
This is function of my solution:
$(function () {
var $result = $('#form');
$('#table').on('click-row.bs.table', function (e, row, $element) {
$('.success').removeClass('success');
$($element).addClass('success');
//alert('Selected name: ' + getSelectedRow().text);
function getSelectedRow() {
var index = $('#table').find('tr.success').data('index');
return $('#table').bootstrapTable('getData')[index];
}
$result.html(
'<table border="0" align="left" style="padding: 10px; margin: 10px; font-size: 14px; color: #0f0f0f">' + '<h3>'+
'<tr align="left" style="padding: 10px; margin: 10px;">' + '<td style="font-weight: bold;">Name</td>' + '<td> </td>' + '<td>' + getSelectedRow().name + '</td>' + '</tr>' +
'<tr align="left" style="padding: 10px; margin: 10px;">' + '<td style="font-weight: bold;">Structure</td>' + '<td> </td>' + '<td>' + getSelectedRow().stargazers_count + '</td>'+ '</tr>'+
'<tr align="left" style="padding: 10px; margin: 10px;"> '+ '<td style="font-weight: bold;">Class</td>' + '<td> </td>' + '<td>' + getSelectedRow().forks_count + '</td>'+ '</tr>'+
'<tr align="left" style="padding: 10px; margin: 10px;"> '+ '<td style="font-weight: bold;">Description</td>' + '<td> </td>' + '<td>' + getSelectedRow().description + '</td>'+ '</tr>'+
'</h3>' + '</table>'
);
})
});
You can use modals of boostrap, will open a modal. Check the documentation on http://getbootstrap.com/javascript/#via-javascript, just add the html, css and js references and call this code:
$('#table').on('click-row.bs.table', function (e, row, $element){ $('#myModal').modal('show') //Will be call the modal when you click a row
})
And you can pass all the information to the modal via javascript. Hope you understand me. :)
Not sure if I get what you need but i add this code on the
html:
<div id="form">
<input type="text" placeholder="Title1" id="titleForm1"></input>
<input type="text" placeholder="Title2" id="titleForm2"></input>
<input type="text" placeholder="Title3" id="titleForm3"></input>
<input type="text" placeholder="Title4" id="titleForm4"></input>
</div>
js:
$('#table').on('click-row.bs.table', function (e, row, $element) {
/*$result.html(
'<pre>' +
JSON.stringify(row, null, 1).replace(/,|}|{/g, " ")
//JSON.stringify(row).replace(/,/g, "<br/>")
+ '</pre>'
);*/
$('#titleForm1').val(row.name);
$('#titleForm2').val(row.stargazers_count);
$('#titleForm3').val(row.forks_count);
$('#titleForm4').val(row.description);
console.log(row);
})
Hope it helps you.
I'm new to jQuery and JS. So I have this task to create tabel row using a dialog form. On every row the last cell must contain a button. My question is how can I add id for this specific button. I've tried selecting the button and adding .attr('id','delete'), but this changes the id of the button that opens the dialog.
So how can I add id only to the newly created button?
< script type = "text/javascript" >
function validateForm(form) {
var errors = [];
$(form.elements).each(function() {
var $this = $(this);
if (!$this.val()) {
var msg = $this.prev().html() + ' е задължително поле';
errors.push(msg);
}
});
return errors;
}
function saveForm(form) {
var nextNumber = $('table tr').length;
var rowTpl = '<tr>' +
'<td>' + nextNumber + '</td>' +
'<td>' + $('#brand', form).val() + '</td>' +
'<td>' + $('#model', form).val() + '</td>' +
'<td>' + $('#year', form).val() + '</td>' +
'<td>' + $('#kms', form).val() + '</td>' +
'<td>' + '<button>' + '<span>' + 'Delete' + '</span>' + '</button>' + '</td>' +
'</tr>';
$('table').append(rowTpl);
}
$(function() {
$('#add-btn').button({
icons: {
primary: 'ui-icon-circle-plus'
}
}).on('click', function() {
$('#form-container').dialog('open')
});
$('#form-container').dialog({
autoOpen: false,
modal: true,
buttons: [{
text: 'Save',
click: function() {
var form = $(this).find('form').get(0);
var errors = validateForm(form);
if (errors.length) {
return alert(errors.join("\n"));
}
saveForm(form);
form.reset();
$(this).dialog('close');
}
}, {
text: 'Close',
click: function() {
$(this).find('form').get(0).reset();
$(this).dialog('close');
}
}]
});
})
$('#delete').button({});
$("#delete").click(function() {
$(this).parents('tr').first().remove();
});
< /script>
<style type="text/css"> table {
border-collapse: collapse;
}
th {
padding: 0.2em;
}
td {
margin: 0.2em;
padding: 0.2em;
text-align: center;
border: 1px solid grey;
}
.ui-widget-header,
.ui-widget-content {
padding: 0.8em;
}
.float-left {
float: left;
}
.float-right {
float: right;
}
</style>
<div id="container" class="ui-widget">
<div class="ui-widget-header ui-helper-clearfix">
<h3 class="float-left">ALL CARS</h3>
<button class="float-right" id="add-btn">
<span>Add New Address</span>
</button>
</div>
<div class="ui-widget-content">
<table width="100%">
<tr>
<th>#</th>
<th>Марка</th>
<th>Модел</th>
<th>Година</th>
<th>Километри</th>
<th>Премахни</th>
</tr>
<tr>
<td>1</td>
<td>BMW</td>
<td>i8</td>
<td>2015</td>
<td>10 000</td>
<td>
<button class="float-center" id="delete">
<span>Delete</span>
</button>
</td>
</tr>
</table>
</div>
<div id="form-container" title="Add new car">
<form action="">
<div>
<label for="brand">Марка</label>
<input type="text" id="brand" />
</div>
<div>
<label for="model">Модел</label>
<input type="text" id="model" />
</div>
<div>
<label for="year">Година</label>
<input type="number" id="year" />
</div>
<div>
<label for="kms">Километри</label>
<input type="number" id="kms" />
</div>
</form>
</div>
</div>
Thank you!
Add id to the button in your rowTpl variable like following.
var rowTpl = '<tr>' +
'<td>' + nextNumber + '</td>' +
'<td>' + $('#brand', form).val() + '</td>' +
'<td>' + $('#model', form).val() + '</td>' +
'<td>' + $('#year', form).val() + '</td>' +
'<td>' + $('#kms', form).val() + '</td>' +
'<td>' + '<button id="delete'+nextNumber+'">' + '<span>' + 'Delete' + '</span>' + '</button>' + '</td>' +
'</tr>';
It will add button id as delete1, delete2, delete3,......
ids are singular so you should not be setting the same id on multiple elements. Second the onclick you are adding with that id is not going to be attached to the button that you create after that code runs. Just like if the phone rings and you are not there, you will not answer it.
Use event delegation to detect what one was clicked and you can use closest to get access to the row the button resides in.
//attach the click handler to the table and listen for a click on a button
$("table").on("click", "button", function () {
var button = $(this); //The button that was clicked
var row = button.closest("tr"); //The row the button is in.
row.remove(); //delete the row
});
id must be unique in the entire document, so setting id to "delete" for all of these buttons is incorrect. You can set a class. When you are creating it, you could just create it as <button class='delete'>, and then use $(".delete") to find all buttons.
You can also set the action directly in the code:
var rowTpl = '<tr>' +
'<td>' + nextNumber + '</td>' +
'<td>' + $('#brand', form).val() + '</td>' +
'<td>' + $('#model', form).val() + '</td>' +
'<td>' + $('#year', form).val() + '</td>' +
'<td>' + $('#kms', form).val() + '</td>' +
'<td>' + '<button onclick="$(this).closest(\'tr\').remove();">' + '<span>' + 'Delete' + '</span>' + '</button>' +
'</td>' +
'</tr>';