Fill the fields of a form from mysql query result - php

In my project it has an interface(designation.php) which has a form. When a user enters a 'designation code'(which is a primary key) and click the 'update' button, the
remaining fields should be filled accordingly. I understand that Ajax will be needed for this.
but the problem is, i'm done with retrieving the result only as a single row from the database by using following query. but, this is not my objective.
while($row = mysqli_fetch_assoc($run1)) {
echo "<tr id='tr'>";
foreach($row AS $cell) echo "<td>$cell</td>";
echo "</tr>\n";
}
Following is the 'designation.php'..
<form action="crud.php" method="post">
<table>
<th >DESIGNATION</th>
<tr>
<td >Designation Code</td>
<td ><input type="text" name="des_code" /></td>
</tr>
<tr>
<td >Designation</td>
<td><input type="text" name="desig" /></td>
</tr>
<tr>
<td >Salary Code</td>
<td><input type="text" name="s_code" /></td>
</tr>
<tr>
<td >Salary Scale</td>
<td><input type="text" name="s_scale" /></td>
</tr>
<tr>
<td >Salary point </td>
<td><input type="text" name="s_point" /></td>
</tr>
<tr>
<td>Date</td>
<td > <input type="date" name="date" /></td>
</tr>
<tr>
<td><input type="submit" name="update" value="Update" /></td>
</tr>
</table>
I attempted many solutions but have not gotten the intended result. Any help is appreciated.

$(document).ready(function(){
("#form1").submit(function({
var id=<?php echo $_POST['des_code']; ?>;
$.ajax({
url: 'update.php',
type:'POST',
data: {id:id},
success : function (data)
{
var a=data.split('[BRK]');
$("#s_scale").val(a[0]);
// like wise store all your fields..
}
})
})
upadte.php will contain
$id=$_POST['id']; //designation id from jqyery
$q=mysqli_query("your goes here..");
while($row = mysqli_fetch_array($q))
{
$cell=$row[0];
$cell.="[BRK]".$row[1];
$cell.="[BRK]".$row[2];
}
echo $cell;
give id to your text field so from jquery you can add value directly.. and give form id also so you can fire onsubmit event...
i didn't try this code but hope it will work fine...

To transfer more than one value use json!
Jquery Code::
$(function(){
id="XXXX";
$("form").on("submit",function(e){
e.preventDefault();
$.getJson("update.php",{"id":id},function(response){
$("#value1").val(response.value1);
$("#value2").val(response.value2);
// like wise store all your fields..
})
})
})
Update.php::
$q=mysqli_query("your query");
$row = mysqli_fetch_array($q);
echo json_encode($row);
$row will be an array containing value1, value2 and so on!!

Related

Need to get the Checked input and checkbox value using jquery in php

Am having table data (retrieve data from mysql table and fetch in to table). table contains several records.I want to display checked checkbox value with input box value and checkbox when i clicking button in php. Checked checkbox value and checked input has deen displayed correctly using join function. but checked with checkbox is not showing correctly. In my code, when i clicking button all checked check values are displayed. my problem to display only checked checkbox with checkbax using join function.
My table:
<table border="0" cellpadding="10" cellspacing="1" width="500" class="tblListForm">
<tr class="listheader">
<td></td>
<td>Username</td>
<td>First Name</td>
<td>Last Name</td>
<td>Permissions</td>
<td>CRUD Actions</td>
</tr>
<?php
$i=0;
while($row = mysqli_fetch_array($result)) {
if($i%2==0)
$classname="evenRow";
else
$classname="oddRow";
?>
<tr class="<?php if(isset($classname)) echo $classname;?>">
<td><input type="checkbox" class="chk_id" name="chk_id" id="chk_id" value="<?php echo $row["userId"]; ?>" /></td>
<td><?php echo $row["userName"]; ?></td>
<td><input type="text" name="firstName" class="firstName" id="firstName" value="<?php echo $row["firstName"];?>" /></td>
<td><?php echo $row["lastName"]; ?></td>
<td><input type="checkbox" name="grant" class="grant" id="grant" value="Y" /></td>
<td><img alt='Edit' title='Edit' src='images/edit.png' width='15px' height='15px' hspace='10' /> <img alt='Delete' title='Delete' src='images/delete.png' width='15px' height='15px'hspace='10' /></td>
</tr>
<?php
$i++;
}
?>
</table>
<input type="button" id="save_value" name="save_value" value="Save" />
my jquery code what i have tried:
$('#save_value').click(function () {
alert("Checkbox running");
var chk_id = [];
var firstName = [];
var grant = [];
$.each($("input[ id='chk_id']:checked"), function () {
chk_id.push($(this).val());
firstName.push($(this).parent().parent().find("#firstName").val());
grant.push($(this).parent().parent().find($("#grant").is(':checked'));
});
alert(chk_id);
alert(firstName);
alert(grant);
});
Here,
am getting checked checkbox and checked input value. my problem to dispaly the checked checkbox with check value.
Thanks#
You made a few small mistakes:
You can't have multiple elements with the same ID, IDs must be unique. So I removed all duplicate IDs from your HTML (id="chk_id",id="firstName",id="grant") and in your JS, used the classes instead.
You missed a closing bracket in grant.push($(this).parent().parent().find($(".grant").is(':checked')));.
.find($(".grant").is(':checked')) isn't working as you expect, and also not necessary.
Use this instead: .find(".grant:checked").
And finally, the reason why your alert showed two values whether the checkboxes were checked or not: grant.push( ... ); always pushes something into the array, if the jQuery-selector matched nothing and would return false, that value would still be pushed into the array.
In fact, if you correct all three points above, and don't check the permission checkbox, the value in the array will be undefined. If you do check the box, it will be Y.
So, in order to make it work, you just have to put the grant.push( ... ); inside an if-clause, where you check for ".grant:checked":
if ($p.find(".grant:checked").length) {grant.push($p.find(".grant:checked").val());}
- $p stands for $(this).parent().parent(), I stored a reference in a var.
- .length checks if the length of the returned object is greater than 0. Without it, the if-clause would still always be true, because jQuery still returns an object (with value undefined).
See code snippet below for a demo:
$('#save_value').click(function() {
var chk_id=[], firstName=[], grant=[];
$.each($("input[class='chk_id']:checked"),function() {
var $row = $(this).parent().parent();
chk_id.push($(this).val());
firstName.push($row.find(".firstName").val());
if ($row.find(".grant:checked").length) {grant.push($row.find(".grant:checked").val());}
});
console.log(chk_id, firstName, grant);
});
table,input[type=button] {float:left;} /*ONLY SO console.log() DOESN'T COVER BUTTON*/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border="0" cellpadding="0" cellspacing="0" width="500" class="tblListForm">
<tr class="listheader"><td></td><td>Username</td><td>First Name</td><td>Last Name</td><td>Permissions</td></tr>
<tr class="evenRow">
<td><input type="checkbox" class="chk_id" name="chk_id" value="4" /></td>
<td>sardhar</td>
<td><input type="text" name="firstName" class="firstName" value="sardhar" /></td>
<td>mohamed</td>
<td><input type="checkbox" name="grant" class="grant" value="Y" /></td>
</tr>
<tr class="oddRow">
<td><input type="checkbox" class="chk_id" name="chk_id" value="3" /></td>
<td>fg</td>
<td><input type="text" name="firstName" class="firstName" value="vb" /></td>
<td>vb</td>
<td><input type="checkbox" name="grant" class="grant" value="Y" /></td>
</tr>
</table>
<input type="button" id="save_value" name="save_value" value="Save" />
jsfiddle: https://jsfiddle.net/3utno9at/

adding values of inputs in each row in corresponding textbox using jQuery

I have to add values of inputs in each row in corresponding textbox (under the heading total) using jquery. I used jQuery as below. class 'value' used for inputs to be typed and class 'values' used for the values displayed (1st two colums).
jQuery code is given below:
jQuery(document).ready(function($) {
var $total = $('#total_mark_<?php echo $student['student_code'];?>'),
$value = $('.value');
$values = $('.values');
$value.on('input', function(e) {
var total = 0;
var t=0;
$value.each(function(index, elem) {
if(!Number.isNaN(parseFloat(this.value, 10)))
total = total + parseFloat(this.value, 10);
});
$values.each(function(index, elem) {
t = t + parseFloat(this.value, 10);
});
total=total+t;
$total.val(Math.round(total));
});
});
When I use this code, I am getting an output only in the last textbox(total-textbox in last row only), where all the values (all input fields)summed up and total is showing in a textbox only.
How to add values of inputs in each row in corresponding textbox using jQuery to show output in corresponding "total"textbox?
I created one demo here, from this demo you can check how to traverse throw DOM element and how to get values from it.
$( document ).ready(function() {
// Traverse throw all rows
$('.student_marks tbody tr').each(function(){
// Get current row
var student = $(this);
var total_points = 0;
$(student).find('.marks').each(function(){
total_points+=parseInt($(this).val());
})
$(student).find('.total').html(total_points);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<table class="table student_marks" >
<thead>
<tr>
<th>Student Name</th>
<th>Math</th>
<th>History</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td class="name">John</td>
<td><input value="50" readonly class="marks"/></td>
<td><input value="50" readonly class="marks"/></td>
<td class="total"></td>
</tr>
<tr>
<td class="name">Mac</td>
<td><input value="60" readonly class="marks"/></td>
<td><input value="50" readonly class="marks"/></td>
<td class="total"></td>
</tr>
<tr>
<td class="name">Sena</td>
<td><input value="40" readonly class="marks"/></td>
<td><input value="70" readonly class="marks"/></td>
<td class="total"></td>
</tr>
<tr>
<td class="name">Devy</td>
<td><input value="80" readonly class="marks"/></td>
<td><input value="90" readonly class="marks"/></td>
<td class="total"></td>
</tr>
</tbody>
</table>
</div>

Generating text box in php and codeigniter

I want to dynamically generate a row of text boxes in a table when clicking a button.For example i have a table to enter the list items.When i click add button, a new row is inserted into the table.Can you please help me.I am working on php and codeigniter..
The foolowing is the script which I have used for generating the row.
<SCRIPT language="javascript">
function changeIt()
{
var i = 1;
my_div.innerHTML = my_div.innerHTML +"<br><input type='text' name='mytext'+ i>"
i++;
}
</SCRIPT>
<table align="center" name="table">
<tr>
<td>Code</td>
<td>Name</td>
<td>Quantity</td>
<td>Price</td>
<INPUT type="button" value="Add" onclick="changeIt()"/>
</tr>
</table>
<div id="my_div">
<table>
<tr>
<td></td>
</tr>
</table>
This only generates one text box at a time. I need to display more that one text box in a row?
Try this (New Code)
<SCRIPT language="javascript">
var i = 1;
function changeIt()
{
var my_div = document.getElementById("my_div");
var row = "<tr> <td> <input type='text' name='mycode_"+i+"'></td><td><input type='text' name='myname_"+i+"'></td><td><input type='text' name='myquantity_"+i+"'></td> <td><input type='text' name='myprice_"+i+"'></td> </tr>";
my_div.innerHTML = my_div.innerHTML +row;
i++;
}
</SCRIPT>
<table align="center" name="table" id="my_div" border="2">
<tr>
<td>Code</td>
<td>Name</td>
<td>Quantity</td>
<td>Price</td>
<INPUT type="button" value="Add" onclick="changeIt()"/>
</tr>
</table>
You can try jQuery append method or row javascript -> HTML DOM appendChild() Method

document.getElementById fails to update textbox value

I have a php code that generates table rows:
<table id="listOfProducts" name="listOfProducts" width="100%">
<tr>
<th>Item</th>
<th>Product</th>
<th>Description</th>
<th>Unit Price</th>
<th>Select</th>
<th>Qty</th>
<th>Amount</th>
</tr>
Products on List: 2
<tr class="row1" id="tr1">
<td id="pid1">1</td>
<td id="pname1">Paint Brush</td>
<td id="pdesc1">Premium Brand </td>
<td id="pprice1">24</td>
<td><input type="checkbox" id="chk1" checked></td>
<td><input type="text" style="width:50px;" onkeyup="getall('tr1','ttp1')" id="1"/></td>
<td><input type="text" id="ttp1" name="ttp1" value="00"/></td>
</tr>
<tr class="row1" id="tr2">
<td id="pid2">2</td>
<td id="pname2">Iron Nails</td>
<td id="pdesc2">Stainless</td>
<td id="pprice2">50</td>
<td><input type="checkbox" id="chk2" checked></td>
<td><input type="text" style="width:50px;" onkeyup="getall('tr2','ttp2')" id="2"/></td>
<td><input type="text" id="ttp2" name="ttp2" value="00"/></td>
</tr>
</table>
This successfully loads the values in the table and calls a javascript getall once the onkeyup function is called.
Here is the javascript code
function getall( strId, prdno){
var tmpObj = document.getElementById(strId);
var myobj = $("#listOfProducts").find("tr#" + strId);
alert("reported id for testing: " + tmpObj.getAttribute("id"));
//alert (prdno);
var prdid= myobj.find('td:eq(0)').text();
var prdname= myobj.find('td:eq(1)').text();
var prddesc= myobj.find('td:eq(2)').text();
var prduprice = parseFloat(myobj.find('td:eq(3)').text());
var quan = myobj.find('td:eq(5) input').val();
var ans=prduprice * quan;
document.getElementById(prdno).value=ans;
}
I don't know what's the real issue. I checked if the id of the containing textbox is successfully passed and it is...
You could try using jquery to update it: $('#'+prdno).val(ans);
i just copy and pasted your code and added the jquery include (v1.7.2) at the top and it totally works in Opera, FF and Chrome

How to create and remove row dynamically using jquery

This is my code
<table id="cont">
<tr>
<td><input type="text" name="no" id="no"/></td>
<td><input type="text" name="qty" id="qty"/></td>
</tr>
</table>
This is my jQuery Code
$(document).ready(function() {
var no="";
$('#no').keyup(function(){
no = $("#no").val();
for(var i=1; i<no; i++)
{
++j;
$('<tr class="field"><td></td><td><input name="qty[]" type="text" id="qty[0]" /></td></tr>').fadeIn('slow').appendTo('#cont');
}
});
if(i==1)
{
$('.field').remove();
}
});
I would like to create and remove row dynamically depending on an input field(no id) and it works fine upto 19 but if i input 20 then it create 20 with extra 1 row as well as i remove zero from 20 then it should be kept 2 rows but it display all rows(21).
How can i solve it , Please any help?
The main problem with your code is you only ever add rows. Here's a solution that provides a bit of timeout after keyup, then replaces all the rows. It's not entirely clear what your overall objective is with this UI.
Note that top row is wrapped in <thead> and <tbody> is used for data rows:
var row = '<tr class="field"><td>Row text</td><td><input name="qty[]" type="text" /></td></tr>';
var num_rows=0;
$('#no').keyup(function () {
num_rows= $(this).val();;
if (!isNaN(num_rows)) {/* make sure is a number, can add extra condition to limit number*/
setTimeout(createRows, 300);/* slight delay to give user time to type*/
} else {
alert('numbers only please')
}
});
function createRows(){
var rowHtml='';
for ( i=0;i<num_rows;i++){
rowHtml+=row;
}
$('#cont tbody').html( rowHtml)
}
Demo:http://jsfiddle.net/H4MHs/
EDIT: I suspect that this approach is completely off track from what you really want, but follows your methodology. Since objective was never spelled out that's all we can go on
You will probably want to convert the value from your field into an integer using parseInt before you use it in the loop.
I'm pretty sure jQuery's .val() will always return a string.
I have the feeling that this is what you need:
Html:
Number of field:<div id='nbElem'></div>
<table id="cont">
<tr>
<td><input type="text" name="no" id="no"/></td>
<td id='field'></td>
</tr>
</table>
Js:
$('#no').keyup(function(){
var $val = parseInt($(this).val(),10);
var $nbQtity = $('.qtity').length;
if($val <= $nbQtity){
for(var i = $val; i < $nbQtity; i++){
$('#q_'+i).remove();
}
}else{
for(var i = $nbQtity; i < $val; i++){
$('<input name="qty[]" class="qtity"'
+' type="text" id="q_'+i+'" />')
.fadeIn('slow')
.appendTo('#field');
}
}
$('#nbElem').text($val);
});
http://jsfiddle.net/pYtbs/
This is the simplest and the easiest way of adding rows
<table id="options-table">
<tbody>
<tr>
<td>Input-Box-One</td>
<td>Input-Box-Two</td>
<td></td>
</tr>
<tr>
<td><input type="text" name="input_box_one[]" /></td>
<td><input type="text" name="input_box_one[]" /></td>
<td><input class="del" type="button" value="Delete" /></td>
</tr>
<tr>
<td><input type="text" name="input_box_one[]" /></td>
<td><input type="text" name="input_box_one[]" /></td>
<td><input class="add" type="button" value="Add More" /></td>
</tr>
</tbody>
If we want more rows then we have to add new row to the table.
Put this code in script
$('.add').live('click',function(){
$(this).val('Delete');
$(this).attr('class','del');
var appendTxt = "<tr><td><input type="text" name="input_box_one[]" /></td><td><input type="text" name="input_box_two[]" /></td><td><input class="add" type="button" value="Add More" /></td></tr>";
$("tr:last").after(appendTxt); });
Delete a row from Table.
$('.del').live('click',function(){
$(this).parent().parent().remove(); });

Categories