convert checked rows to input fields - php

I am showing data from database into table with the checkbox in front of every row. All I want is to change the checked rows columns with class click into input fields on clicking the edit button. I am very new to jQuery. I don't have much concepts about it. So help me please.
Here is the jQuery code I've tried:
$(function () {
$("input[name='check[]']:checked").each(function (){
$('#edit').click(function(){
var OriginalContent = $('.click').text();
$('.click').addClass("cellEditing");
$('.click').html("<input type='text' value='" + OriginalContent + "' />");
$('.click').children().first().focus();
$('.click').children().first().keypress(function (e) {
if (e.which == 13) {
var newContent = $('.click').val();
$('.click').parent().text(newContent);
$('.click').parent().removeClass("cellEditing");
}
});
$('.click').children().first().blur(function(){
$('.click').parent().text(OriginalContent);
$('.click').parent().removeClass("cellEditing");
});
});
});
});
And here is the html:
echo '<div class="table-responsive">';
echo '<table class="table table-bordered table-hover"><thead><tr>
<th>ID</th><th>Name</th><th>Category</th><th>Description</th><th>Price</th><th>Status</th><th colspan="2">Image</th></tr></thead><tbody>';
while($row = mysqli_fetch_array($retval))
{
echo '<tr><td>'.$row["ID"].'</td>
<td >'.$row["Name"].'</td>
<td>'.$row["Category"].'</td>
<td>'.$row["Description"].'</td>
<td class="click1">'.$row["Price"].'</td>
<td class="click">'.$row["Status"].'</td>
<td><img style="width: 3em; heigth: 3em;" class="img-responsive" src="'.$row["Imagepath"].'" alt="'.$row["Name"].'"/></td>
<td><input class="checkbox" name="check[]" id="check[]" type="checkbox" value='.$row["ID"].'/></td></tr>';
}
echo '</tbody></table>';
echo '</div>';
?>
<center><input class="btn btn-default" name="deletebutton" type="submit" value="DELETE" />
<input class="btn btn-default" name="edit" id="edit" type="button" value="EDIT" />
<input class="btn btn-default" name="updatebutton" type="submit" value="UPDATE"/></center>
</form>

Basically you need two functions to run...
when "edit" is clicked: convert all "editable" columns to INPUTs, if that row is ":checked"
when ENTER is pressed while editing one of your "editable" INPUTs: revert it to a string
I simplified your HTML a bit for clarity. An explanation of the jQuery needed is inline.
Also, here's a working jsFiddle: http://jsfiddle.net/msz76tgp/2/
HTML
<table>
<tr>
<td class="editable status">something</td>
<td class="editable price">2</td>
<td class="checkbox"><input type="checkbox"/></td>
</tr>
<tr>
<td class="editable status">something else</td>
<td class="editable price">3</td>
<td class="checkbox"><input type="checkbox"/></td>
</tr>
</table>
<a id="edit" href="#edit">edit</a>
jQuery
$(function () {
// When edit is clicked...
$('#edit').on('click', function(){
// For each ":checked" checkbox...
$('.checkbox INPUT:checked').each( function(){
// Get the parent row...
var $row = $(this).closest('tr');
// And that row's "editable" columns...
var $editable= $row.children('.editable');
// Add the "editing" class...
$editable.addClass('editing');
// And change all strings to INPUT fields.
$editable.each( function(){
$(this).html('<input value="'+$(this).text()+'"/>');
});
});
});
// Also...
// Any time an .editing INPUT receives a keypress...
$('table').on('keypress', '.editing', function(e){
// If the key pressed is ENTER...
if( e.which == 13 ){
// Get the current row...
var $row = $(this).closest('tr');
// Get the editable columns...
var $editable = $row.children('.editable');
// Remove the class...
$editable.removeClass('editing');
// Change back to string...
$editable.each( function(){
$(this).html( $(this).find('INPUT').val() );
});
}
});
});

I didnt really use your code, since you're writing html with php which is hard to maintain and isnt my preferred style (id rather write html and then put php inside) but this should get help you with your question: http://jsfiddle.net/swm53ran/28/.
comments in the code show what's going on. in essence, im using jquery to add the input with the data that is already in there. but since you are using php, you can just modify the code below by inserting <?php echo();?> inside the html code built in the javascript section.
<tr>
<td class="name">php echo name here</td>
<td class="description">php echo description here</td>
<td class="data">php echo data here</td>
<td>Edit Info</td>
</tr>
$('.edit').on('click', function() {
var row = $(this).closest('tr');
***NOT NECESSARY SECTION OF CODE BECAUSE YOU'RE USING PHP (JUST FOR DEMO)****
//collect data thats there (you dont have to do this if you have php,
//then you can just code in <?php echo();?> into your html building in
//javascript) because i have no php here
var name = row.find('.name').html();
var description = row.find('.description').html();
var data = row.find('.data').html();
***END OF NOT NECESSARY SECTION****
//construct inputs to be inserted into cells
//since you're using php, you modify the below code to something like this:
//var nameInput = '<input type="text" value="<?php echo('name');?>"/>';
//but you have to be careful because ^ this code wont work because of the
//nested parenthesis escape each other, so just put like <?php echo('name');?>
//into another variable and stick the variable in instead.
var nameInput = '<input type="text" value="'+ name +'"/>';
var descriptionInput = '<input type="text" value="'+ description +'"/>';
var dataInput = '<input type="text" value="'+ data +'"/>';
//remove all contents and append inputs
row.find('.name').html('').append(nameInput);
row.find('.description').html('').append(descriptionInput);
row.find('.data').html('').append(dataInput);
});
hope this helps!

Related

Delete a table row is not working with jquery on button click

I have problem when I click on button the table row is not deleted tr id and button id are both same value. please tell where I am doing wrong
<tr id="<?php echo $result->id;?>">
<td><input type="text" name="feature[]" class="text-input medium-input datepickur" value="<?php echo $result->feature;?>" /></td>
<td><button type="button" name="remove" id="<?php echo $result->id;?>" class="btn btn-danger button_remove">X</button></td>
</tr>
Jquery code
$(document).ready(function() {
$('.button_remove').click(function() {
var btn_id = $(this).attr("id");
$('#' + btn_id + '').remove();
});
});
Thanks in advance
id need to be unique per element if you are going to use them in jQuery, and hense your code is not working (As tr and td sharing same value for id).
Simplify you code through closest()
$(document).ready(function(){
$('.button_remove').click(function(){
$(this).closest('tr').remove();
});
});
Note:- Remove id from tr and td both. As it's not needed at all. It will make your HTML structure correct and cleaner.
Thats because you are using same id for tr and button....Try to use data-attributes here
<tr id="<?php echo $result->id;?>">
<td><input type="text" name="feature[]" class="text-input medium-input datepickur" value="<?php echo $result->feature;?>" /></td>
<td><button type="button" name="remove" data-row="<?php echo $result->id;?>" class="btn btn-danger button_remove">X</button></td>
<tr>
And then use jQuery like this
$(document).ready(function() {
$('.button_remove').click(function() {
var btn_id = $(this).data("row");
$('#' + btn_id + '').remove();
});
});
$(document).ready(function() {
$('.button_remove').click(function() {
$(this).parents().eq(1).remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" value="1"/></td>
<td><button type="button" class="button_remove">X</button></td>
</tr>
<tr>
<td><input type="text" value="2"/></td>
<td><button type="button" class="button_remove">X</button></td>
</tr>
</table>

table tr is not replaced properly as expected

I have to one public_page.php page and one action.php page. If a user press submit button in public_page.php it sends information to action.php page by jquery post method. After successful processing the action.php page sends one tr data which should be replaced in table of public_page.php.
page: public_page.php
<div id="result"></div>
<table>
<thead><tr><th>S/N</th><th>Name</th><th>Address</th><th>Mobile</th><th>Action</th></tr></thead>
<tbody>
<tr id="1"><td>1</td><td>Mr.X</td><td>Japan</td><td>95684256</td><td><a class="edit" href="">Edit</a></td></tr>
<tr id="5"><td>1</td><td>Mr.Y</td><td>USA</td><td>123856641</td><td><a class="edit" href="">Edit</a></td></tr>
<tr id="8"><td>1</td><td>Mr.Z</td><td>UK</td><td>456862043</td><td><a class="edit" href="">Edit</a></td></tr>
</tbody>
</table>
jquery code (without $(document).ready line here):
$("body").on("click",".edit",function(event){
event.preventDefault();
var url = 'action.php';
var trid = $(this).closest('tr').attr('id');
$.post(url,
{
trid: trid,
},function(data){
$("#result").html(data).show();
});
});
after that the data of table row is come in '#result' div for editing. Let. tr id=5 (Mr.Y) is now for editing. So here it is comes in #result div as follows:
<div id="result">
<form id="5000">
Name:<input type="text" name="name" value="Mr.Y" /><br />
Address:<input type="text" name="adrs" value="USA" /><br />
Mobile:<input type="text" name="mobile" value="123856641" /><br />
Age:<input type="text" name="age" value="30" /><br />
<input type="submit" value="Submit" />
</form>
</div>
Now when user edit the information and press Submit, it sends the form information to action.php page by jquery. what is doing action.php page, after getting trid (which is actually id of database row that is to be edited) it process the data and produce callback data for public_page.php like this:
page: action.php
echo '<div class="success_msg">Data Updated Successfully!</div>';
echo '<div class="trid">5</div>';
echo '<div class="trcontent"><tr id="5"><td>1</td><td>Mr.Y</td><td>Tokeyo</td><td>123856641</td><td><a class="edit" href="">Edit</a></td></tr></div>';
and jquery code of public_page.php process the data like this:
var url = 'action.php';
var id = $(this).closest('form').attr('id');
var form_id = "#"+id ;
var data = $(form_id).serializeArray();
$.post(url,
data,function(callbackdata){
var msg = $(callbackdata).filter(".success_msg").html();
var trid = $(callbackdata).filter(".trid").html();
var trdata = $(callbackdata).filter(".trcontent").html();
$("#result").html(msg).show();
$('#'+trid).replaceWith(trdata);
});
as per query code, it should replace the tr which id is 5. But although it is replacing the tr but not in tabular format, it is replacing as text format like this:
page: public_page.php
<div id="result"></div>
<table>
<thead><tr><th>S/N</th><th>Name</th><th>Address</th><th>Mobile</th><th>Action</th></tr></thead>
<tbody>
<tr id="1"><td>1</td><td>Mr.X</td><td>Japan</td><td>95684256</td><td><a class="edit" href="">Edit</a></td></tr>
1Mr.YTokeyo123856641<a class="edit" href="">Edit</a>
<tr id="8"><td>1</td><td>Mr.Z</td><td>UK</td><td>456862043</td><td><a class="edit" href="">Edit</a></td></tr>
</tbody>
</table>
I think ...... is not inserting with replaced data.
How to resolve this issue, so that after replacing tr id="5" looks like a table row, not a string.
I'd suggest making an edit that will deal with this in a simpler way.
In your php code, instead of returning a div, what you should return is data.
<?php
$data = new stdClass();
$data->successMsg = 'Data Updated Successfully!';
$data->trid = 5;
$data->trContent = '<tr id="5"><td>1</td><td>Mr.Y</td><td>Tokeyo</td><td>123856641</td><td><a class="edit" href="">Edit</a></td></tr>';
echo json_encode($data);
Then in your JS code, you can go directly at the data instead of filtering it out of your HTML.
$.post(url,
data,
function(callbackdata){
var msg = callbackdata.successMsg;
var trid = callbackdata.trid;
var trdata = callbackdata.trContent;
$("#result").html(msg).show();
$('#'+trid).replaceWith(trdata);
},
'json');
The reason you're having problems is because of the way jQuery handles invalid HTML. <div><tr><td>1</td><td>2</td></tr></div> is not valid.
$('<div><tr><td>1</td><td>2</td></tr></div>').html() // outputs `12`

How to make dynamic list transferring "unknown" id's work with static script

Note #1: var id = $("#mysqlid").val(); is supposed to be the value from the hidden field from the form where the delete button has been pushed.
The id is unknown, since it is the auto_increment id from the ever changing database. To make it unique.
<script type="text/javascript">
$(document).ready(function(){
$(document).on("click", "#delete", function(){
var id = $("#mysqlid").val(); // Note #1
$.ajax({
type:"post",
url:"http://www.mydomain.no/action.php",
data:"id="+id+"&action=delete",
success:function(data){
showList();
// showlist() returns an updated list of entries from the database after the selected row is deleted.
}
});
});
});
</script>
<table id="list">
<theader>
<tr>
<td>Name</td><td>Action</td>
</tr>
</theader>
<tbody>
<!-- Content from action.php start here -->
<tr>
<td>Test data</td>
<td>
<form>
<input type="hidden" id="mysqlid13" value="13">
<a href="#" id="delete">
<img style="cursor:pointer;" src="gfx/delete.png" alt="Delete">
</a>
</form>
</td>
</tr>
<tr>
<td>Test data 2</td>
<td>
<form>
<input type="hidden" id="mysqlid14" value="14">
<a href="#" id="delete">
<img style="cursor:pointer;" src="gfx/delete.png" alt="Delete">
</a>
</form>
</td>
</tr>
<!-- Content from action.php ends here -->
</tbody>
</table>
I've removed all the excess code, as to not clutter the issue at hand.
I'm sure this is an easy fix for someone more advanced in javascript than me.
As per my previous suggestion, you can assign a common class name to the elements that will need to be grabbed and passed back to the server. The class name wouldn't have to be unique just known. If you give all the elements you wish to perform this action on the same class name you can select those elements, get their values, and pass them back in your ajax call.
Given html:
<form>
<input type="hidden" id="mysqlid13" class='deleteMe' value="13">
<a href="#" id="delete">
<img style="cursor:pointer;" src="gfx/delete.png" alt="Delete">
</a>
</form>
Your js could become:
$(document).on("click", "#delete", function(){
var id = $(this).closest("form").find(".deleteMe").val();
/*make your ajax call or whatever*/
});
Now if you only have that one hidden input element per form element you could even simplify it and not even use an identifier and select by type:
$(document).on("click", "#delete", function(){
var id = $(this).closest("form").find("input[type='hidden']").val();
/*make your ajax call or whatever*/
});
I'd prefer to do this in a bit better approach, like this
Note it's invalid HTML to have duplicate ID in a document, please change it to class
<form>
<input type="hidden" name="id" value="14" />
<input type="hidden" name="action" value="delete" />
<a href="#" class="delete">
<img style="cursor:pointer;" src="gfx/delete.png" alt="Delete" />
</a>
</form>
$(document).on("click", ".delete", function (e) {
e.preventDefault(); // prevent default action
var that = this;
$.ajax({
type: "post",
url: "http://www.mydomain.no/action.php",
data: $(that).closest('form').serialize(),
success: function (data) {
showList();
// showlist() returns an updated list of entries from the database after the selected row is deleted.
}
});
});
set data format , it may not pass like query string and complete url may not work cause of CORS
$.ajax({
type:"post",
url:"/action.php",
data:{"id":id,"action":"delete"},
success:function(data){
showList();
}
First you need to change you links to use a class, not an id, as ids must be unique. So you html becomes
<a href="#" class="delete">...
Then your js becomes
$(document).on("click", ".delete", function(){
var id = $(this).prev("input").val();
...
}

Javascript not accepting my function arguments?

i am passing the class and id of chechboxes to the js function and try to make it dynamic to work for id and class of any checkbox to check all and uncheck all check boxes
here is the html
<input type="checkbox" name="reply_status[]" <?=$checked;?> class="memebers" value="<?=$status[$e]['mail_sent_id']?>">
</td>
<td>
<input type="checkbox" name="send_invoice[]" <?=$checked_send_invoice;?> class="send_invoice" value="<?=$status[$e]['mail_sent_id']?>">
</td>
<td>
<input type="checkbox" name="invoice_paid[]" <?=$checked_invoice_paid;?> class="invoice_paid" value="<?=$status[$e]['mail_sent_id']?>">
</td>
<td>
<input type="checkbox" id="check_all_re" name="check_all" onclick="checkall_members('memebers','check_all_re')">
Check All
</td>
<td>
<input type="checkbox" id="check_all_sv" name="check_all" onclick="checkall_members('send_invoice','check_all_sv')">
Check All
</td>
<td>
<input type="checkbox" id="check_all_ip" name="check_all" onclick="checkall_members('invoice_paid','check_all_ip')">
Check All
</td>
and here is the js function
<script type="text/javascript">
function checkall_members(chechboxclass, chechboxid) {
// var id = document.getElementById("check_all");
alert();
chechboxid = $('#' + chechboxid);
chechboxclass = $('.' + chechboxclass);
if (chechboxid.checked) {
chechboxclass.attr('checked', 'checked');
}
else {
chechboxclass.removeAttr('checked');
}
}
any help would be appreciated
Replace your if..else block with the following.
chechboxclass.prop('checked', chechboxid.prop('checked'));
By the way, it's checkbox and not chechbox.
To improve your code even more, get rid of the inline events:
$('input[name="check_all"]').on('change', function() {
$($(this).data('toggleAll')).prop('checked', this.checked);
});
Now you just need to add data-toggle-all=".send_invoice" etc. to those checkboxes. The param value should be the selector of the checkboxes you want to toggle with that checkbox.
If you have all the name="check_all" elements a class, you could also speed up the selector by using input.whatever_class instead of input[name="check_all"]
i have sorted out the simplest solution for my problem that is
<script type="text/javascript">
function checkall_members(chechboxclass, chechboxid) {
var checkbox = document.getElementById(chechboxid);
chechboxclass = $('.' + chechboxclass);
if (checkbox.checked) {
chechboxclass.attr('checked', 'checked');
}
else {
chechboxclass.removeAttr('checked');
}
}
</script>
i have to get the id elememt within same library of javascript thats why it was not working
var checkbox = document.getElementById(chechboxid);
thanks guys for helping me

Create row ID for dynamic JS Table

I have working script that the user completes inputs on a form and when they submit the form and the content of the form inputs are entered as a table row.
Is there any way of, I think within the JS to make each row have a unique ID and add a delete button to the last colum of each row so the user can delete an individual row.
Thanks for saving a life!!!!
HTML Form
<form id="my_form" action="table_form.php" method="post">
<div style="width:10%; float:left;">
Quantity<br />
<input name="field_1" type="text" id="field_1" size="3" />
</div>
<div style="width:20%; float:left;">
Part Number<br />
<input type="text" id="field_2" name="field_2" />
</div>
<div style="width:30%; float:left;">
Notes<br />
<input name="field_3" type="text" id="field_3" size="45" />
</div>
<div style="width:20%; float:left;">
Unit Price<br />
<input type="text" id="field_4" name="field_4" />
</div>
<div style="width:20%; float:left;">
<br />
<input type="submit" value="Add Row" />
</div>
</form>
<!--
Here we create our HTML table.
Note the ID of the table. This will be used in our javascript file
Our table only contains a header row. All other content will be added dynamically
--><? $rowid = 1; ?>
<table width="100%" id="my_table">
<tbody id="my_table_body">
<tr>
<th width="5%"><div align="left">Qty</div></th>
<th width="19%"><div align="left">Part Number</div></th>
<th width="46%"><div align="left">Notes</div></th>
<th width="15%"><div align="left">Unit Price</div></th>
<th width="15%"><div align="left">Row Total</div></th>
</tr>
</tbody>
</table>
JS
window.addEvent('domready', function(){
$('my_form').addEvent('submit', function(e){
e.stop();
this.set('send', {
onComplete: function( response ){
var data = JSON.decode(response);
inject_row( $('my_table_body'), data );
}
});
var valid_form = true;
$$('#my_form input').each(function(item){
if( item.value == '' ) valid_form = false;
});
if( valid_form ) {
this.send();
} else {
alert('Fill in all fields');
}
});
var inject_row = function( table_body, data ){
var row_str = '<tr width="100%">';
data.each( function(item, index){
row_str += '<td>'+item+'</td>';
});
row_str += '<td><input type="submit" name="deleterow" id="deleterow" value="Delete" /></td></tr>';
var newRow = htmlToElements( row_str );
newRow.inject( table_body );
}
var htmlToElements = function(str){
return new Element('div', {html: '<table><tbody>' + str + '</tbody></table>'}).getElement('tr');
}
});
PHP
<?php
/**
* If nothing is being posted to this script redirect to
* our HTML page.
*/
if( ! $_POST ){
header('Location: newquote.php');
}
// create an empty array for our results
$results = array();
/**
* Stick the values from _POST into our results array
* while also stripping out any html tags
*
* This is where you would perform any required processing
* of the form data such as server side validation or updating
* a database.
*/
foreach( $_POST as $field ){
$results[] = strip_tags( $field );
}
// Echo our results as a JSON encoded string.
echo json_encode( $results );
?>
I agree with J-P, it sounds like you don't need an unique id here.
Since the question is tagged "jquery" I suggest using the live event binding, e.g.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function() {
$(".deleterow").live("click", function() {
$(this).parents("tr:first").remove();
});
});
function foo(id) {
$("#"+id).append('<tr><td>'+(new Date()).getSeconds()+'</td><td>x</td><button class="deleterow">delete</button></td></tr>');
}
</script>
</head>
<body>
<table id="t1">
<tr><td>a</td><td>A</td><td><button class="deleterow">delete</button></td></tr>
<tr><td>b</td><td>B</td><td><button class="deleterow">delete</button></td></tr>
<tr><td>c</td><td>C</td><td><button class="deleterow">delete</button></td></tr>
</table>
<button onclick="foo('t1')">add</button>
</body>
</html>
The function passed to $(document).ready() is invoked when ...well, as the name states, when the document (dom) is ready.
$(".deleterow").live("click", ... : Whenever a click event occurs on an element with the css class "deleterow" the function passed as second parameter is invoked. In this case
function() {
$(this).parents("tr:first").remove();
}
When the function is invoked the this-context is the element where the event occurred. parents("tr:first") returns the first/"nearest" tr element in the ancestor-axis of the current element. remove() is probably self-explaining...
edit: ok, now that the jquery tag is gone....
http://www.jaycarlson.net/blog/2009/04/06/live-events-in-mootools/ shows a live-event binding for mootools. Using that the "new" solution is quite similar to the jquery script
window.addEvent('domready', function() {
// add an onclick handler for all current and future button elements
// within the table id=t1
$('t1').addLiveEvent('click', 'button', function(e){
// a button in t1 has been clicked, this=button element
// get the "nearest" tr in the parent/ancestor-axis
// and remove it
$(this).getParent("tr").dispose();
});
});
This should be unique enough for this project:
var newDate = new Date;
var id = newDate.getTime();
Then it would just be a matter of adding it the row in your loop and linking it to your delete button.
I always use the php function uniqid(). It generates a unique id based on the time in microseconds. PHP Documentation.
You could loop through your results in PHP and add the result from uniqid() to each result before using json_encode().

Categories