jQuery pass input value based on table row - php

I know very little jquery so please excuse me if I don't make much sense.
I have a table that it's rows are populated from a php db query (the number of rows will vary) in this case there are two rows of data. Here is a portion of the php generated html table.
<table border=1 width=800px id=workout>
<tr>
<th width=300px id=clients>Client</th>
<th width=200px id=movements>Movements</th>
<th>X Completed</th>
</tr>
<tr>
<td><input type="hidden" name="client_id[]" class="clientval" value="1"></td>
<td>
<select name="movement[]" width=200 class='typeval' onchange='changeMovement()'>
<option value="select">Select...</option>
<option>Key Movement</option>
<option>Movement -1</option>
<option selected="selected" >Movement -2</option>
<option>Movement -3</option>
<option>Movement -4</option>
</select>
</td>
<td><label id="count"></label></td>
</tr>
<tr>
<td><input type="hidden" name="client_id[]" class="clientval" value="8">
<td>
<select name="movement[]" width=200 class='typeval' onchange='changeMovement()'>
<option value="select">Select...</option>
<option>Key Movement</option>
<option>Movement -1</option>
<option selected="selected" >Movement -2</option>
<option>Movement -3</option>
<option>Movement -4</option>
</select>
</td>
<td><label id="count"></label></td>
</tr>
I am passing the values of movement and client_id to a POST jquery so I can run a php query on the data and return result. How do I pass along the value of selected movement and client_id based on the row that the select menu is in.
For example: if user changes movement drop down menu on the 2nd row I want to send the client_id and the selected>Movement< to the jQuery function. Right now it is just getting the first row of my table and that is all.
Here is my edited jQuery:
Edited:
<script type="text/javascript">
var typeval,clientval, class_id;
$('.typeval').on('change', function(){
movement = $(".typeval option:selected").val();
client_id = $(this).parents('tr').find('input.clientval').val();
class_id = $(<? echo $class_id; ?>).val();
//console.log($(this).parents('tr').find('input.clientval').val(), $(this).val());
$.ajax(
{ url: "movement_count.php",
type: "post",
data: {typeval:typeval, client_id: clientval, class_id :},
dataType: "json",
});
success: (function(output) {
alert(output);
$(".count").html(output);
})
});
</script>

Since you're using jQuery I'd do it like this. Remove the inline JavaScript and bind to the change event of the select elements.
var typeval,clientval;
$('select.typeval').change(function() {
//console.log($(this).parents('tr').find('input').val(), $(this).val());
typeval = $(this).val();
clientval = $(this).parents('tr').find('input').val();
});​
$(this).parents('tr').find('input').val(); //will give you the
client_id
$(this).val(); // will give you the value of the select item
You can then just drop those values into your AJAX call.
jsFiddle example

Well, you need to do the following:
1. Remove all onchange='changeMovement()', you won't need them anymore.
2. Just echo the class_id from PHP.
3. Fix the way you get the client_id as below.
Code:
$(document).ready(function() {
$('.typeval').change(function() {
var movement = $(this).val();
var client_id = $(this).parent().siblings().find('.clientval').val();
var class_id = <?php echo $class_id; ?>;
/* Do your AJAX call here */
});
});​​​​​​​​​​​​

Give your select and input elements a unique id using php. Something like:
<input type="hidden" id="client_id$client_id" ...
<select name="movement[]" id="mov$client_id" ...
Then in your javascript function use php to include the client_id like this:
changeMovement(client_id)
then you can use the client_id to change whatever movement that corresponds like this:
var client = $("#client_id"+client_id).val();
var movement = $("#mov"+client_id).val();
For the unique ID, you probably want to use whatever variable is populating the value field of your hidden inputs of each row. I say that without knowing exactly where those numbers are coming from.

Using James' solution it would look like this:
then the jquery looks like this:
var movement = this.value
var client_id = this.parent().find(".clientval")

Check this working example.. http://jsfiddle.net/sushanth009/BZ5Wt/
You can get the ClientId of the selected row by using this line..
var client = $(this).parent().parent().find('.clientval').val();

Related

Ajax multiple dropdown return value- php mysql

i had 4 table like this
Table
And then im going to fill this form
Form
the workflow is, when i select Item Type and Treatment, the price should be filled based on the ServicePrice Table, I can get the Price from ServicePrice, but when I check XHR on network, it shows the value of Price but its data just show for 1st time, I mean when the modal opened, it shows the first data, when the option changed, the Price value keep like the 1st time modal open. so I want whenever the Item Type or Treatment changed, I want to make the price box filled dynamically
here's my form
<tr>
<td>Item Type</td>
<td>
<select name="ItemTypeID" class="form-control" id="ItemType" >
<option selected=""></option>
<?php
$sql2 = mysql_query("select * from itemtype");
while($record = mysql_fetch_array($sql2)){
?>
<option value="<?php echo $record['ID']; ?>" title="<?php echo $record['DefaultSpec']; ?>"> <?php echo $record["Name"]; ?> </option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td>Treatment</td>
<td>
<select name="TreatmentID" class="form-control" id="Treatment">
<?php
$sql2 = mysql_query("select * from treatment");
while($record = mysql_fetch_array($sql2)){
?>
<option value="<?php echo $record['ID']; ?>"> <?php echo $record["Name"]; ?> </option>
<?php } ?>
</select>
</td>
</tr>
and then my ajax
$("#ItemType, #Treatment").change(function(){
var ItemType = $(this).val();
var Treatment = $(this).val();
console.log(Treatment);
console.log(ItemType);
$.ajax({
type: "POST",
dataType: "html",
url: "GetPrice.php",
data: {ItemTypeID: ItemType, TreatmentID: Treatment},
success: function(result){
console.log(result);
$("#Price").val(result);
});
});
my GetPrice.php
<?php include "../Content/connection.php";
$a="SELECT * FROM ServicePrice WHERE ItemtypeID = '".$_POST["ItemTypeID"]."' AND TreatmentID = '".$_POST["TreatmentID"]."'";
$q=mysql_query($a);
while($record=mysql_fetch_array($q)){
echo $record['Price'];
}
?>
EDIT :
im making it like this it give me correct answer but the Price value triggered only if treatment dropdown changed, how can i make it trigger by booth dropdown?
$("#ItemType").change(function(){
var ItemType = $(this).val();
$("#Treatment").change(function(){
var Treatment = $(this).val();
the $(this).val() inside the change event handler will not work to get data for both the fields,
instead fetch the data of ItemType and Treatment individually
$("#ItemType, #Treatment").on('change', function(){
var ItemType = $("#ItemType").val();
var Treatment = $("#Treatment").val();
$.ajax({
type: "POST",
url: "GetPrice.php",
data: {ItemTypeID: ItemType, TreatmentID: Treatment},
success: function(result){
$("#Price").val(result);
}
});
});

Dynamically Populating each rows from database using php-Ajax

I have a table that is dynamically populated from mysql database.User are expected to select a staff number, which automatically goes to the DB and fetches his staff number.I have like 10rows. it works fine for the first row but not the subsequent other others.
Please, take a look at the code and advice where I am missing it.
Thanks
<tr>
<th nowrap="nowrap">S/N</th>
<th nowrap="nowrap">VNO</th>
<th nowrap="nowrap">Name</th>
<th nowrap="nowrap">Staff No</th>
</tr>
<tr>
<?php
$c=0;
$st =mysqli_query($connection,"SELECT * FROM tab_flt WHERE mainloc='".$_SESSION['location']."' AND status='Active'");
while($r = mysqli_fetch_array($st)){ $c++?>
<td><?php echo $c;?></td>
<td><input type="text" name="flt[]" value="<?php echo $r['fltno'];?>" class="form-control" readonly="readonly" /></td>
<td><select name="opname[]" class="form-control" id="subloc">
<option>Select...</option>
<?php
$fs = getOperators($_SESSION['location']);
while($f = mysqli_fetch_array($fs)){?>
<option value="<?php echo $f['name'];?>"><?php echo $f['name'];?></option>
<?php };?>
</select></td>
<td id="staffno"></td>
</tr>
Ajax side:
<script type="text/javascript">
$(document).ready(function() {
$("#subloc").change(function(){
var sname = $("#subloc option:selected").val();
$.ajax({
type:"POST",
url:"process-opno.php",
data:{opname:sname}
}).done(function(data3){
$("#staffno").html(data3);
});
});
});
</script>
The above fetches the first rows when subloc id is selected successfully into staffno id.
But it does not do it for the remaining lines. What can i do so, that it will recognise the second line, third line etc and fetches the corresponding staff number into the staffno id .
Thanks.
Please try this:
PHP Part I have added classes for select box and select box ajax result
<tr>
<?php
$c=0;
$st =mysqli_query($connection,"SELECT * FROM tab_flt WHERE mainloc='".$_SESSION['location']."' AND status='Active'");
while($r = mysqli_fetch_array($st)){
$c++;
?>
<td><?php echo $c;?></td>
<td><input type="text" name="flt[]" value="<?php echo $r['fltno'];?>" class="form-control" readonly="readonly" /></td>
<td>
<select name="opname[]" class="form-control js-sel-box" data-id="<?php echo $c;?>">
<option>Select...</option>
<?php
$fs = getOperators($_SESSION['location']);
while($f = mysqli_fetch_array($fs)){
?>
<option value="<?php echo $f['name'];?>"><?php echo $f['name'];?></option>
<?php
};
?>
</select>
</td>
<td class="js-sel-box-ajax-result-<?php echo $c;?>"></td>
<?php
}//End While
?>
</tr>
Ajax Part:
<script type="text/javascript">
$(document).ready(function() {
$(".js-sel-box").change(function(){
var sname = $(this).val();
var result_id = $(this).attr("data-id");
$.ajax({
type:"POST",
url:"process-opno.php",
data:{opname:sname}
}).done(function(data3){
$(".js-sel-box-ajax-result-"+result_id).html(data3);
});
});
});
</script>
The same old problem with unique ids, change the id into a class,find all your elements based on the changed select
<script type="text/javascript">
$(document).ready(function() {
$("td select.form-control").change(function(){
var sname = $(this).val();
var el = $(this);
$.ajax({type:"POST",url:"process-opno.php",data:{opname:sname}})
.done(function(data3){
$(this).parent().next("td").html(data3);
});
});
});
</script>
Yes, its better to use class identifier instead of id to identify multiple DOM elements; but in yours it can be workable with minimum changes-
// use
var sname = $(this).val();
//put this line just var sname
var $object =$(this);
// instead of
var sname = $("#subloc option:selected").val();
// this is because- $('#subloc option:selected').val(); always returns the first
//dropdownList/optionlist from the DOM array, you can use `this` to track which DOM has been change recently
// another change in your code $object is $(this) equivalent but will not work inside ajax so you need to create $object as in code above..
// put this line
$($object).parents('tr').find("#staffno").html(data3);
//instead of
$("#staffno").html(data3);
// above line will search parent tr and will look for DOM element with id staffno a

How to get the location(col,row) of an element, which is inside a table?

I am studing jquery to post input tables. All inputs need to be posted with their indexes. I am guessing that i cant use ids or classes of input elements to post values with cell location info. .Because Input tables are generated dynamically according to user answer.
For Example;
User enters '4' value to a question and a 3col 4row input table is generated.
<table>
<tr><td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td>
</tr>
<tr><td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td>
</tr>
<tr><td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td>
</tr>
<tr><td><input type="text"></td> <td><input type="text"></td> <td><input type="text"></td>
</tr>
</table>
And by using jquery handler i can store the values...
$(function () {
$("input").change(function() {
// save this.value() in an array.
array.push(this.value());
});
});
I stuck at this moment because i have to store values with their (x,y)indexes in the table. Shortly; values of this 2 dimension table must be converted to a 2dim. data array in server-side.
Something like...
$(function () {
$("input").change(function() {
array[this.col][this.row] = this.value();
});
});
To sum up;
Is it possible to get the location(col,row) of an element, which is inside a table?
You can use index() method as follows
$(function () {
$("input").change(function () {
var row = $(this).closest('tr').index(); //index of row
var col= $(this).closest('td').index(); //index of column
// your code
});
});
JSFiddle Demo
Try something like this:
$(function () {
var $rows=$('tr');/* refine if using column heading row to something like $('tr:gt(0)')*/
$("input").change(function() {
var $row=$(this).closest('tr');
var rowIndex=$rows.index($row);
var colIndex=$(this).parent().index();
/* do something with indexes*/
});
});
if you want store value of column and rows in array you can use a multidimensional array (array of arrays).
first of all you insert in default array other arrays that rapresent yuour rows and then when the field change you'll store data in array first data:rows second data column.
<script type="text/javascript">
$(document).ready(function(){
var array=[]
for(a=0;a<$('table tr').length;a++){
array[a]=[]
}
$("input").change(function() {
var val=$(this).val()
var row=$(this).parents('tr').index()
var column =$(this).parent('td').index()
array[row][column] = val
console.log(array)
});
})
</script>

jquery dynamic added row display price form db on each row select option

Hi i need some help in jquery task, i created table with dynamic row add. i want when i select option value this price display in this row next column, ever select option value will be different in each row
my code is here
<script type="text/JavaScript">
$(".name").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "test.php",
data: dataString,
cache: false,
dataType:"json",
success: function(data)
{
$(".price").val(data.price);
return false;
}
});
});
</script>
HTML:
<table>
<tr>
<th>
select item
</th>
<th>
price
</th>
</tr>
<tbody>
<td>
<select name="item[]">
<option value="1">
item name
</option>
</select>
</td>
<input type"text" name="price[]">
<td>
</td>
</tbody>
</table>
From the picture it looks like you would several dropdowns with textbox next to it and you want to load the price of each item separately, for that you need to do things:
Change
$(".name").change(function()
to
$("select[name^='item']").change(function()
This means to target a select tag which has name starting with item.
Change
$(".price").val(data.price);
to
$(this).closest('tr').find("input[name^='price']").val(data.price);
This means we find the closest tr tag of the select and then find an input with name starting from price within the tr tag, so your select dropdown value always get stored in the next textbox.
DEMO (This link is just to give you an idea of how it works and AJAX is commented because JSFiddle will not run it).
With, dynamic rows, you should use .on method. Adding some classes to the elemens for esealy find them.
This code should work:
<table id="unit-price">
<tr>
<th>
select item
</th>
<th>
price
</th>
</tr>
<tbody>
<tr>
<td>
<select class="name" name="item[]">
<option value="1">item name</option>
</select>
</td>
<td>
<input type="text" class="price" name="price[]">
</td>
</tr>
</tbody>
</table>
<script type="text/JavaScript">
$("#unit-price").on('change', '.name', function () {
var $this = $(this);
$.ajax({
type : "POST",
url : "test.php",
data : {
id : $this.val()
},
cache : false,
dataType : "json",
success : function (data) {
$this.parent()
// Get parent tr
.closest('tr')
// Then, find price textbox with class 'price'
.find('.price').val(data.price);
}
});
});
</script>
I think you could solve your problem using jQuery's nextUntil() function.
In your case, you could call $(this).nextUntil(".price").val(data.price);
I'm not too sure on this one so let us know if this works.

Autosave from php to mysql without page change or submit button

Basically I have a list of data that is shown via a foreach statement from a table in my database. I want a dropdown list next to each that has some values in them that need to be saved to a field in my table, however I want to autosave the value in the dropdown list to the field as soon as the value in it is changed. Can anyone point me to a tutorial or something that might help?
I am using php and mysql to create the system, but will happily use JavaScript if required
I have had a look at this: dynamic Drive Autosavehttp://www.dynamicdrive.com/dynamicindex16/autosaveform.htm which is similar to what i want, however i need it to actually store that data in my database not temporary storage.
Any Guidance appreciated,
Ian
BIG EDIT
So, thankyou for the replys but I have no clue about ajax call.....I found this:How to Auto Save Selection in ComboBox into MYSQL in PHP without submit button?.
can i get it to work?
<script>
$(document).ready(function(){
$('select').live('change',function () {
var statusVal = $(this).val();
alert(statusVal);
$.ajax({
type: "POST",
url: "saveStatus.php",
data: {statusType : statusVal },
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
<?php foreach ( $results['jobs'] as $job ) { ?>
<td width="25%"><?php echo $job->job_id</td>
<td>
<select name="status" id="status">
<option value=''>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select>
<div id="autosavenotify"></div>
</td>
</tr>
<?php } ?>
and on the page saveStatus.php:
<?php
if (isset($_POST['statusType'])) {
$con=mysql_connect("localhost","username","mypass","rocketdb3");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jobs", $con);
$st=$_POST['statusType'];
$query = "UPDATE jobs SET status=$st WHERE job_id=$id";
$resource = mysql_query($query)
or die (mysql_error());
}
?>
Where is the $id in saveStatus.php ?
You need to pass the statusType and job_id via AJAX to update correctly in the saveStatus.php.
For example:
<script>
$(document).ready(function(){
$('select').on('change',function () {
var statusVal = $(this).val();
var job_id = $(this).id;
alert(statusVal);
$.ajax({
type: "POST",
url: "saveStatus.php",
data: {statusType : statusVal, job_id: job_id },
success: function(msg) {
$('#autosavenotify').text(msg);
}
})
});
});
</script>
<?php foreach ( $results['jobs'] as $job ) { ?>
<td width="25%"><?php echo $job->job_id; ?></td>
<td>
<select name="status" id="<?php echo $job->job_id; ?>">
<option value=''>--Select--</option>
<option value='0'>Approve</option>
<option value='1'>Reject</option>
<option value='2'>Pending</option>
</select>
<div id="autosavenotify"></div>
</td>
</tr>
<?php } ?>
*Note: .live() is deprecated, use .on() instead.
And saveStatus.php
$st = (int)$_POST['statusType'];
$id = (int)$_POST['job_id'];
$query = "UPDATE jobs SET status=$st WHERE job_id=$id";
You will need to use JavaScript (+ jQuery for easier working) to achieve this.
Catch the 'change' of the value using JavaScript and fire an AJAX call to a PHP script that saves the value to the MySQL db.
Use jQuery! On the drop-down onchange event do a ajax call and update the record in DB. Here is a link to jQuery Ajax method.

Categories