<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 ?
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. :)
Related
I am trying to alert something but on click function is running only once on the first button. but I have buttons on many rows.
I am fetching Data through Laravel from Database in a table. Only one button runs a function, then nothing happens with other buttons.
Jquery:
jQuery(document).ready(function(e) {
$('#restore-data').on('click', function(e) {
var val = $("#thisr").attr('value');
alert(val);
});
});
View:
<table id="recover-table" class="table" >
<thead>
<tr class="bg-info">
<th>Teacher Name</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($trashs as $trash)
<tr id="thisr" value="{{$trash->id}}">
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap "><button type="submit" class="" name="id"
value="{{$trash->id}}" id="restore-data">Delete</button></td>
</tr>
#endforeach </tbody></table>
Right now even alert is not working, but I want to achieve Refresh table after a record is deleted from Table.
Update: Now Alert is working fine, but when I delete a record by pressing a button, only one row is deleting. the function runs once.
Complete Js:
jQuery(document).ready(function(e) {
$('#restore-data').on('click', function(e) {
let teacher_id=$(this).attr('value');
console.log('Restore button clicked!')
e.preventDefault();
$.ajax(
{
url: "/teachers/recover/" + $('#restore-data').attr("value"),
type: 'GET', // Just delete Latter Capital Is Working Fine
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: teacher_id,
success: function (data) {
console.log(data.msg);
console.log(teacher_id);
if(data.msg){
$('#thisr').remove();
$('#response').empty();
$(".toast").toast('show');
$('#response').append(data.msg);
}
},
error: function (xhr) {
console.log("Error Restoring Record");
//console.log(xhr.responseText);
},
});
});
});
You can try to use class 'restore-data'
$(document).ready(function(e) {
$(document).on('click', '.restore-data', function(e) {
var val = $('#thisr').val();
alert(val);
});
});
As id should be unique for each element.
You can try something like
#foreach($trashs as $trash)
<tr>
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap ">
<button type="button" data-trash-id="{{$trash->id}}" class="restore-data">Delete</button>
</td>
</tr>
#endforeach
and JS as
$(document).on('click', '.restore-data', function(e) {
var trash_id = $(this).attr('data-trash-id');
alert(trash_id);
});
Change this line.
var val = $("#thisr").attr('value');
to (since you have value attribute in button):
var val = $(this).attr('value');
or (since you have value attribute td):
var val = $(this).parent('tr#thisr').attr('value')
To remove a row.
$('#restore-data').on('click', function(e) {
var _this = $(this);
...
if(data.msg){
_this.parent('tr#thisr').remove();
....
Also change button type to button.
<button type="button" class="" name="id"
value="{{$trash->id}}" id="restore-data">Delete</button></td>
You gave same id to all button and id must be unique of particular button so you can define unique id with key of array and pass it to Function
#foreach($trashs as $key=>$trash)
<tr id="thisr{{$key}}">
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap ">
<button type="button" class="" name="id" value="{{$trash->id}}" id="restore-data{{$key}}" onclick="restoreData({{$key}})">Delete</button>
</td>
</tr>
#endforeach
function restoreData(key){
var val = $("#restore-data"+key).attr('value');
alert(val);
// you can use either
$("#restore-data"+key).closest('tr').remove();
// OR
$('#thisr'+key).remove();
}
At the folloing code,I try to delete a row using ajax .serialize() but it only deletes the first row.Using jQuery(this).closest('form').find('input[name="id"]').val(); also returns "Undefined" for ID.
Ajax Code
function AjaxDelete() {
var rowId = $("#sil").serialize();
var confirmation = confirm("Are you sure of deleting the following user:"+rowId);
if (confirmation) {
$.ajax({
type:'POST',
url:'sil.php', //deleting file
data: rowId,
success:function(cevap){
alert("User has been successfully removed.ID="+rowId);
}
});
}
return confirmation;
};
Table Structure
echo '<table id="kullanicilar" align=center>
<thead>
<tr>
<td></td>
<td>ID</td>
<td>Kullanıcı Adı</td>
<td>Yönetici</td>
<td colspan=4>İşlemler</td>
</tr>
</thead>
';
while($results->fetch()){ //fetch values
echo '<tr>
<td><input type="checkbox" name="select[]" value="'.$id.'"></td>
<td>'.$id.'</td>
<td>'.$kullanici_adi.'</td>
<td>'.$yonetici.'</td>
<td><form method="post" id="sil"><input type="hidden" name="id" value="'.$id.'" class="id"></form><img src="img/delete.png" title="Sil"></td>
<td><img src="img/edit.png" title="Düzenle"></img></td>
<td>Gönderilerini Gör</td>
<td><a target="_blank" href="#" class="gor">Profilini Gör</a></td>
</tr>
'
;
}
echo '</table><br/>';
In your while loop, you are giving same id to inputs which is wrong. you can try:
<a href="#" onclick="return AjaxDelete("'.$id.'");" class="link"><form method="post" id="sil">
and then in your ajax:
function AjaxDelete(x) {
var rowId = x;
On entering the customer name in textbox it searches for customer info. I have generated successfully using JQuery by passing the entire table through Json variable, as I dont want any page refresh. Now I want to select the customer id generated from mysql db (php) through radio button, but the radio button event is not working. For testing purpose I have put a static table having the same radio button properties in that particular div(place for dynamic record generation using JQuery) and working fine. Hence I found that the data received through JQuery got some problem. Hope I am clear. Please find a way. Thanks in advance.
below is the code
abc.php
<input type="text" placeholder="full name" id="fullName" name="fullName" class="txt" style="width: 250px" />
<input type="button" id="btSelect" value="Select" class="button-crystal" />
<div id="disp"></div>
script.js
$('#btSelect').click(function () {
var form_data = {
genCustDetails: $('#fullName').val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: "xyz.php",
data: form_data,
dataType: "json",
success: function (response)
{
$('#disp').html(response);
}
});
return false;
});
xyz.php
if (isset($_POST['genCustDetails'])) {
$out="";
$result = mysql_query("select * from dbcustdetails where name like '$_POST[genCustDetails]%'");
while ($row = mysql_fetch_assoc($result)) {
$out.='
<table style="background-color:#eee; margin-bottom:5px;">
<tr>
<th class="td3">Customer ID</th>
<td class="td4">
'.$row["custID"].' <input type="radio" id="cust_ID" name="cust_ID" value="'.$row["custID"].'" />
</td>
</tr>
<tr>
<th class="td3">Name</th>
<td class="td4">'.$row["name"].'</td>
</tr>
<tr>
<th class="td3">Phone No.</th>
<td class="td4">'.$row["phno"].'</td>
</tr>
<tr>
<th class="td3">Email</th>
<td class="td4">'.$row["email"].'</td>
</tr>
<tr>
<td colspan="2" style="padding:0;">
<b>Address</b><br/>'.$row["addr"].'
</td>
</tr>
</table>';
}
echo json_encode($out);
}
Maybe You should'nt bind the event properly for the dynamic elements in the DOM.
Try Like this
$('body').on('change','.radiobuttonClassorID',function(){
//actions
});
that is because your newly generated radio button is not having any event handler assigned to it.
you have to assign an event handler after the ajax call (on ajax success).
something like
$('input[type="radio"]').unbind('click').click(function(){
//Your handler code
})
I would like to sort a table with data row from MySQL then change the order and submit it.
I used jQueryUI.sortable to make those tr tag (row) draggable.
But when I submitting the form, some of them didn't changed order.
Why? I tried to figure it out, I var_dump the data I submitted and I found a problem:
The tr tag (row) I moved from the original order, won't pass to PHP so var_dump will not show the row ID.
To make it easier to understand, I post my code here:
HTML Code
<table>
<thead>
<tr>
<th>Subject</th>
<th>Content</th>
</tr>
</thead>
<tbody id="sortable">
<tr>
<td>
Hello World
<input name="displayorder[]" type="hidden" value="1" />
</td>
<td>I come from Mars!</td>
</tr>
<tr>
<td>
Hello Mars
<input name="displayorder[]" type="hidden" value="2" />
</td>
<td>I come from Jupiter!</td>
</tr>
<tr>
<td>
Hello StackOverflow
<input name="displayorder[]" type="hidden" value="3" />
</td>
<td>I come from North Korea ...</td>
</tr>
</tbody>
<tbody>
<tr>
<td colspan="2"><input type="submit" value="Submit!" />
</tr>
</tbody>
</table>
I omitted the form content cause it is not important
JavaScript (Sortable Library loaded)
$(document).ready(function() {
$('#sortable').sortable({
helper: fixHelper,
axis: 'y',
opacity: 0.6,
}).disableSelection();
});
var fixHelper = function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
};
PHP
$displayorder = $_POST["displayorder"];
if($displayorder != "") {
$order = 1;
foreach($displayorder as $value) {
mysql_query("UPDATE message SET displayorder=$order WHERE announcementid=$value");
$order++;
}
}
I will prefer not using Ajax to do this because I have dozens of similar page to do the same task.
Thanks in advance.
Well I decided to code it every page.
The code now:
JavaScript
$(document).ready(function() {
$('#sortable').sortable({
helper: fixHelper,
axis: 'y',
opacity: 0.4,
update: function(event, ui){
var data = $(this).sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: '/update.php?action=displayorder'
});
},
}).disableSelection();
});
var fixHelper = function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
};
PHP
foreach($_POST["displayorder"] as $i => $value) {
mysql_query("UPDATE message SET displayorder=$i WHERE announcementid=$value");
$i++;
}
So I just got done with figuring out some javascript issues with my form in this topic: How Can I Insert Multiple Rows Into a DB from my HTML Form with Multiple Rows Dynamically?
But since I had such a multi-part question I have been asked to create a new topic. Below is my new code that I am using where I am stuck and wanting to be able to submit my form, which has the capability if adding multiple rows, to my database and add those HTML rows to rows in the SQL database, respectively.
PREVIEW: http://cl.ly/image/0K0Z202O1Q3e/Screen%20Shot%202013-03-14%20at%203.00.19%20PM.png
HTML
<html>
<header>
<link rel="stylesheet" href="style.css" type="text/css">
<script type="text/javascript" language="javascript" src="/jquery/js/jquery-1.9.1.js">
</script>
<script src="http://www.mapquestapi.com/sdk/js/v7.0.s/mqa.toolkit.js?
key=Gmjtd%7Cluua2q6bn9%2C8g%3Do5-lzbsh"></script>
<script type="text/javascript" src="js/scripts.js"></script>
<title>Central Office Company Survey</title>
</header>
<body onload="get_company_name();">
<h1>Central Office Company Survey</h1>
<div id='map' style='width:0px; height:0px; position:absolute'></div>
<input type="hidden" id="co_city" name="co_city">
<input type="hidden" id="co_state" name="co_state">
<input type="hidden" id="co_zipcode" name="co_zipcode">
<table>
<th>Company</th>
<th>CO Name</th>
<th>Get Current Location</th>
<th>Lat</th>
<th>Long</th>
<th>Address</th>
<tr>
<td><select id="company_name" name="company_name" /></select></td>
<td><input name="co_name" type="text"></td>
<td><input type="submit" value="Get GPS" onclick="gpslookup();" /></td>
<td><input id="co_lat" name="co_lat" type="text" /></td>
<td><input id="co_long" name="co_long" type="text" /></td>
<td><input id="co_address" name="co_address" type="text" /></td>
</tr>
</table>
<table id="tabledata">
<thead>
<th>Select</th>
<th>Border Location Name</th>
<th>Cable Location</th>
<th>Direction of Vault Wall</th>
<th>Cable Type</th>
<th>Cable Size (pairs)</th>
<th>Cable Gauge</th>
<th>Vertical(s) appeared on Verticals</th>
<th>Approximate Number of Jumpers</th>
<th>Are Protectors Still In?</th>
<th>Metered Distance</th>
<th class="comments">Central Office Comments</th>
</thead>
<tbody id="input"></tbody>
<tbody id="template">
<tr>
<td><input type="checkbox" /></td>
<td><input name="border_location" type="text" /></td>
<td><input name="cable_location" type="text" /></td>
<td><input name="vault_direction" type="text" /></td>
<td><input name="cable_type" type="text" /></td>
<td><input name="cable_size" type="text" /></td>
<td><input name="cable_gauge" type="text" /></td>
<td><input name="vertical" type="text" /></td>
<td><input name="jumpers" type="text" /></td>
<td><input name="protectors" type="text" /></td>
<td><input name="metered_dist" type="text" /></td>
<td><input name="comments" type="text" /></td>
</tr>
</tbody>
</table>
<button id="ActionAddRow">Add Row</button>
<button onclick="deleteRow(); return false;">Delete Row</button>
<button id="ActionSubmit">Submit</button>
</body>
</html>
scripts.js
//Button Functions
$(function () {
var addInputRow = function () {
$('#input').append($('#template').html());
};
addInputRow();
$('#ActionAddRow').on('click', addInputRow);
$('#ActionSubmit').on('click', function () {
var data = $('#input tr').map(function () {
var values = {};
$('input', $(this)).each(function () {
values[this.name] = this.value;
});
return values;
}).get();
$.post('./php/upload_survey.php', {
json: JSON.stringify(data),
delay: 1
}).done(function (response) {
alert("Thank you. Your form has been submitted.");
console.log(response);
});
});
});
//Delete Selected Rows
function deleteRow() {
try {
var table = document.getElementById("tabledata");
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) {
if(rowCount <= 3) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
catch(e) {
alert(e);
}
};
upload_survey.php
//Assign passed parameters
$values = json_decode($_POST['json']);
$stringLogInfo = "INFO: Location: $co_address CO Name = $co_name !!!\n\n";
log_audit($logAuditFile, $logModule, $stringLogInfo);
//Parse and store the ini file, this will return an associative array
ini_set("display_errors", "1");
error_reporting(E_ALL);
//Insert Survey Form Information into the database
$sql="INSERT INTO table_name (company_name,...,...)
VALUES ($values)";
mysql_query($sql) or die ("Unable to Make Query:" . mysql_error());
**So far every time I try to get this working the JS fires successfully, but I get an error in Chrome's Developer Toolbox: Unable to Make Query:Column count doesn't match value count at row 1
This refers to this function in js file: console.log(response);
I think there is no such thing as batch inserts in PHP. There is no equivalent for JAVA's addBatch & executeBatch.
So the right way to do it is simply iteratation over array and insert single row with prepared statement.