Reputation: 4187
<a class="checkModelButton" href="check.php">Check</a>
<div id="model_list"></div>
include jquery and function deleteRow():
jQuery('.checkModelButton').click(function(event){
event.preventDefault();
var url = jQuery(this).attr('href');
jQuery.ajax({
type: 'get',
cache: false,
url: url,
success: function(html){
jQuery('#model_list').html(html);
}
});
});
function deleteRow(id) {
try {
var table = document.getElementById('model_list');
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
jQuery("input[type=checkbox]:checked").each(function() {
jQuery(this).parents("tr").remove();
});
} catch(e) {
alert(e);
}
}
in check.php return html is:
<input type="button" value="Delete Row" onclick="deleteRow('model_list')" />
<table id="model_list">
<thead>
<tr>
<th>#</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" value="1" name="model_id[]" class="item"></td>
<td>Nokia N71</td>
</tr>
</tbody>
</table>
After loadding ajax, I checked on form input and click button Delete Row, but error can't delete this row And error is alert(Table model_list is empty)
, how to fix it ?
Upvotes: 0
Views: 259
Reputation: 330
jQuery has really simplified the selection process for us and also provided a lot of fail-safes that JavaScript doesn't offer without a try/catch block. Since you're already using jQuery, you can really simplify your deleteRow() function by doing the following:
function deleteRow(id) { // the id variable is unnecessary and can be removed
// Grab all the rows in the table (the > sign targets the elements directly inside the current one (not cascading)
var rows = jQuery("#model_list > tbody > tr");
// Iterate through the rows
jQuery(rows).each(function(key, value) {
// Look inside each row for a checked checkbox
if (jQuery(this).find("input:checkbox[checked='checked']").length > 0) {
// If one is found, then remove the whole row (jQuery(this) refers to the current row
jQuery(this).remove();
}
});
}
To make the example above work, I created a temporary table in the same file. Since you are dynamically loading the table rows with data, this should function similar to the static sample below:
<input type="button" value="Delete Row" onclick="deleteRow('model_list')" />
<table id="model_list">
<thead>
<tr>
<th>#</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" value="1" name="model_id[]" class="item"></td>
<td>Nokia N71</td>
</tr>
<tr>
<td><input type="checkbox" value="2" name="model_id[]" class="item"></td>
<td>Nokia N72</td>
</tr>
<tr>
<td><input type="checkbox" value="3" name="model_id[]" class="item"></td>
<td>Nokia N73</td>
</tr>
</tbody>
</table>
Please let me know if this is helpful or if you have any other questions. :)
Upvotes: 2