I have only added a portion of the full code here. What I want the code to do, is once it is submitted, I only want it to update the fields in the table that have been changed, not every item in every row (as some are NULL value, and need to stay that way).
So ultimately - how would I code the PHP process page.
Table is formatted as heli_cust:
cust_id
cust_fname
cust_lname
cust_kg
cust_email
cust_addr
cust_phone
http://jsfiddle.net/qz7k5caj/
HTML:
<table width="100%">
<div class="form_head">Passengers</div>
<table width="100%" cellpadding="4" cellspacing="0" id="px">
<thead>
<tr class="tab_head">
<td width="25px" style="text-align:center; color:#FFFFFF; font-size:11px;">#</td>
<td class="form_label" style="color:#ffffff; font-size:11px;">Cust#</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">First Name</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">Last Name</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">Wgt</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">Address</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">Phone</td>
<td class="form_label" style="color:#FFFFFF; font-size:11px;">Email</td>
<td></td>
</tr>
</thead>
<tbody id="tbl1">
<?php if ($cust = mysql_fetch_assoc($getcust)) {
do { ?>
<tr id="pass">
<td style="vertical-align:middle; text-align:center"><input type="text" name="pass_num[]" readonly="readonly" value="1" class="pass" style="font:Verdana; font-size:11px; border:none; background-color:transparent; width:25px; text-align:center; vertical-align:middle;" tabindex="-1"></td>
<td><input type="text" readonly="readonly" class="form_a" value="<?php echo (int)$cust[cust_id] ?>" style="text-align:right; border:none; background-color:transparent; width:25px" /></td>
<td><input type="text" name="cust_fname[]" class="form_g" value="<?php echo $cust[cust_fname] ?>"/></td>
<td><input type="text" name="cust_lname[]" class="form_g" value="<?php echo $cust[cust_lname] ?>"/></td>
<td><input type="text" name="cust_kg[]" class="form_a" value="<?php echo $cust[cust_kg] ?>"/></td>
<td><input type="text" name="cust_addr[]" class="form_c" style="width:200px" value="<?php echo $cust[cust_addr] ?>"/></td>
<td><input type="text" name="cust_phone[]" class="form_g" value="<?php echo $cust[cust_phone] ?>"/></td>
<td><input type="text" name="cust_email[]" class="form_b" value="<?php echo $cust[cust_email] ?>"/></td>
<td style="vertical-align:middle"><a class="removePax"><img src="images/remove_pax.png" /></a></td>
</tr>
<?php } while ($cust = mysql_fetch_assoc($getcust));
} ?>
</tbody>
</table>
<table width="100%">
<tr><td style="text-align:right"><a id="add"> <img src="images/add_pax.gif"> </a></td></tr>
</table>
<br />
<table width="100%"><tr><td></td><td style="text-align:right"><input type="submit" value="Update" /></td></tr>
</table>
JQuery:
$("#tbl1 tr:even").css({"background-color":"#CCC", "opacity":"0.8"});
$("#tbl1 tr:odd").css({"background-color":"#FFF", "opacity":"0.8"});
$(".pass").each(function(){
$(this).val($(this).closest('tr').index()+1);
});
$("#tbl1 .removePax").on("click",function() {
if($("#tbl1 tr:last").index() >0) {
var tr = $(this).closest('tr');
tr.css("background-color","#FF3700");
tr.fadeOut(500, function(){
tr.remove();
$(".pass").each(function(){
$(this).val($(this).closest('tr').index()+1);
});
$("#tbl1 tr:even").css({"background-color":"#CCC", "opacity":"0.8"});
$("#tbl1 tr:odd").css({"background-color":"#FFF", "opacity":"0.8"});
});
return false;
} else {
if($(this).closest('tr').index() == 0) {
$("#tbl1 tr:eq(0)").find("input").each(function(){
if ($(this).hasClass('pass')) {
} else {
$(this).val('');
};
});
};
};
});
$("#add").click(function(){
$("#tbl1 tr:first").clone().find("input").each(function() {
$(this).val('')}).end().appendTo("#tbl1");
$("#tbl1 tr:even").css({"background-color":"#CCC", "opacity":"0.8"});
$("#tbl1 tr:odd").css({"background-color":"#FFF", "opacity":"0.8"});
$(".removePax").on("click",function() {
if($("#tbl1 tr:last").index() >0) {
var tr = $(this).closest('tr');
tr.css("background-color","#FF3700");
tr.fadeOut(500, function(){
tr.remove();
$(".pass").each(function(){
$(this).val($(this).closest('tr').index()+1);
});
$("#tbl1 tr:even").css({"background-color":"#CCC", "opacity":"0.8"});
$("#tbl1 tr:odd").css({"background-color":"#FFF", "opacity":"0.8"});
});
return false;
} else {
if($(this).closest('tr').index() == 0) {
$("#tbl1 tr:eq(0)").find("input").each(function(){
if ($(this).hasClass('pass')) {
} else {
$(this).val('');
}
}).end();
} else {
var tr = $(this).closest('tr');
tr.css("background-color","#FF3700");
tr.fadeOut(500, function(){
tr.remove();
$(".pass").each(function(){
$(this).val($(this).closest('tr').index()+1);
});
$("#tbl1 tr:even").css({"background-color":"#CCC", "opacity":"0.8"});
$("#tbl1 tr:odd").css({"background-color":"#FFF", "opacity":"0.8"});
});
return false;
}
};
});
$(".pass").each(function(){
$(this).val($(this).closest('tr').index()+1);
});
});
});
Aside from the idea given by #rjdown, In case you're trying to do it using AJAX, you can add an onchange handler, and add a class "changed" to the changed item. Then, just send all the changed data back to your backend. That way you know for sure what you're to send.
Related
I have table from foreach, in this table i create submit with ajax (id="detail"), but why when i submit i just get first row, when i click second row value, i get first row value not second row value ?
<form action="<?php echo base_url() ?>index.php/stock_opname/proses_detail" method="post">
<table class="table table-striped">
<thead>
<tr>
<th>No</th>
<th>SO No</th>
<th>Opname Date</th>
<th>Warehouse</th>
<th>Type</th>
<th>Approve</th>
<th>Close period</th>
<th>Detail</th>
</tr>
</thead>
<tbody>
<?php $no=1; foreach ($show as $key) { ?>
<tr>
<td><?php echo $no ?></td>
<td><input type="text" id="sono" value="<?php echo $key->sono ?>"></td>
<td><input type="text" id="opnamedate" value="<?php echo $key->opnamedate ?>"></td>
<td><input type="text" id="warehousecode" value="<?php echo $key->warehousecode ?>"></td>
<td><input type="text" id="stocktypeid" value="<?php echo $key->stocktypeid ?>"></td>
<td></td>
<td></td>
<td>Detail</td>
</tr>
<?php $no++;} ?>
</tbody>
</table>
</form>
<script type="text/javascript">
//Ajax Load data from ajax
$(document).on('click', '#detail', function(){
var sono = $('#sono').val();
var opnamedate = $('#opnamedate').val();
var wh = $('#warehousecode').val();
var stocktypeid = $('#stocktypeid').val();
alert(sono);
});
you have to make the id also dynamic and also the script sholud be dynamic.Hope you get it
id="detail1"
.on('click', '#detail1', function() ----for first
.on('click', '#detail2', function() ----for second and so on
<form action="<?php echo base_url() ?>index.php/stock_opname/proses_detail" method="post">
<table class="table table-striped">
<thead>
<tr>
<th>No</th>
<th>SO No</th>
<th>Opname Date</th>
<th>Warehouse</th>
<th>Type</th>
<th>Approve</th>
<th>Close period</th>
<th>Detail</th>
</tr>
</thead>
<tbody>
<?php $no=1; foreach ($show as $key) { ?>
<tr>
<td><?php echo $no ?></td>
<td><input type="text" id="sono<?php echo $no; ?>" value="<?php echo $key->sono ?>"></td>
<td><input type="text" id="opnamedate<?php echo $no; ?>" value="<?php echo $key->opnamedate ?>"></td>
<td><input type="text" id="warehousecode<?php echo $no; ?>" value="<?php echo $key->warehousecode ?>"></td>
<td><input type="text" id="stocktypeid<?php echo $no; ?>" value="<?php echo $key->stocktypeid ?>"></td>
<td></td>
<td></td>
<td>Detail</td>
</tr>
<?php $no++;} ?>
</tbody>
</table>
</form>
<script type="text/javascript"> //Ajax Load data from ajax
function getDetails(no){
var sono = $('#sono'+no).val();
var opnamedate = $('#opnamedate'+no).val();
var wh = $('#warehousecode'+no).val();
var stocktypeid = $('#stocktypeid'+no).val();
alert(sono);}
hope this will help
Can you try this ?
$('#detail').click(function(){
var sono = $(this).siblings('#sono').val();
var opnamedate = $(this).siblings('#opnamedate ').val();
var wh = $(this).siblings('#wh').val();
var stocktypeid = $(this).siblings('#stocktypeid ').val();
alert(sono);
});
I do have a dynamic grid that shows items from MySQL table using PHP. I have a icon that is supposed to get data from MySQL based in the id of the current register and fill the fields in the form with related information:
PHP/HTML grid
$output .='<tr id="'.$id.'">';
$output .='<td>'.$description.'</td>';
$output .='<td>'.$description_pt.'</td>';
$output .='<td align="right">US$'.number_format($price, 2, '.', ',').'</td>';
$output .='<td align="center">'.$a_c.'</td>';
$output .='<td align="center">'.$note.'</td>';
$output .='<td align="center">'.$note_pt.'</td>';
$output .='<td align="center" class="icon_grid"><a class="editar" title="Open the register." href="#"><img src="images/Write2.gif" width="16" height="16" /></a></td>';
$output .='<td align="center" class="icon_grid"><a class="delete" title="Delete the register." href="#"><img src="images/Trash.gif" width="16" height="16" /></a></td>';
$output .='</tr>';
The HTML form:
<div id="edita_cadastro">
<form name="form3" id="form3" method="post" action="" >
<table width="50%" border="0" cellspacing="2" cellpadding="0">
<tr>
<td colspan="2"><h3>Edit the current register</h3></td>
</tr>
<tr>
<td align="right"><label for "edt_description"><img src="images/usa.jpg" width="18" height="15" />Description:</label></td>
<td><input type="text" name="edt_description" id="edt_description" size="45" /></td>
</tr>
<tr>
<td align="right"><label for "edt_description_pt"><img src="images/brazil.jpg" width="18" height="15" />Description:</label></td>
<td><input type="text" name="edt_description_pt" id="edt_description_pt" size="45" /></td>
</tr>
<tr>
<td align="right"><label for "edt_price">Price:</label></td>
<td><input type="text" name="edt_price" id="edt_price" size="35" placeholder="ex.: 1.00" /></td>
</tr>
<input type="hidden" name="pack_id" id="pack_id" value="<?php echo $pack_id; ?>" />
<td><input type="hidden" name="editar" value="editar" /></td>
<td><input type="submit" name="submit" id="submit" value="Save" /></td>
</tr>
</table>
</form>
</div>
Now, the PHP get_prices.php
include '../connect_to_mysql.php';
$item_id = $_POST['pk_id']; // Selected item Id
$query = "SELECT * from packages_prices WHERE id='$item_id'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result, MYSQL_ASSOC);
$description = $row['description'];
$description_pt = $row['description_pt'];
$price = $row['edt_price'];
$arr = array( 'edt_description' => $description, 'edt_description_pt' => $description_pt, 'edt_price'=> $price);
echo json_encode( $arr );
Finally, the jQuery script:
$(document).ready(function(e) {
$("#tabela tr[id]").on("click", ".editar", function () { // Tabela is the table's id
var obj = $(this).closest("tr[id]");
$.ajax({
type: "POST",
url: 'get_prices.php',
data: { pk_id: obj.attr("id")},
dataType: "json",
success: function(data, evt) {
if (data.success == "true") {
$("#edt_description").val(data.edt_description);
$("#edt_description_pt").val(data.edt_description_pt);
$("#edt_price").val(data.edt_price);
} else {
alert('error');
}
}
});
});
So, I don't know what may be wrong. The data is not coming and, of course, not filling the fields.
Does anyone knows what is going on?
Thank you
You have a syntax error , your forgot }); at the end of your script , so may it's the reason why it's not working:
<script>
$(document).ready(function(e) {
$("#tabela tr[id]").on("click", ".editar", function () { // Tabela is the table's id
var obj = $(this).closest("tr[id]");
$.ajax({
type: "POST",
url: 'get_prices.php',
data: { pk_id: obj.attr("id")},
dataType: "json",
success: function(data, evt) {
if (data.success == "true") {
$("#edt_description").val(data.edt_description);
$("#edt_description_pt").val(data.edt_description_pt);
$("#edt_price").val(data.edt_price);
} else {
alert('error');
}
}
});
});
});
</script>
<head>
<title> Add User page</title>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<form name='f2' action="insert_ac.php" method="post" >
<script src="validation.js" type="javascript/text"></script>
</head>
<body onload="firstfocus();">
<table align="center" border="0" cellpadding="3" cellspacing="1">
<tr>
<td> First Name</td><td > : </td>
<td> <input type='text' name='fname' id='fid' size="50" style="background-color:#abcddd; height:18px;" value='' maxlength="100" onblur="fname_validation(5,12);"> </td>
</tr>
<tr>
<td> Last Name</td><td> : </td>
<td> <input type='text' name='lname' id='lid' size="50" style="background-color:#abcddd; height:18px; "value='' maxlength="100" onblur="lname_validation(5,12);"> </td>
</tr>
<tr>
<td> Gender</td><td> : </td>
<td> <input type='radio' name='gend' id='m' value='M' checked>Male <input type='radio' name='gend' id='f' value='F'>Female</td>
</tr>
<tr>
<td> Phone Number</td><td> : </td>
<td> <input type='number_format' name='phone' id='phno'size="50" style="background-color:#abcddd; height:18px; " value=''onblur="allnumeric();"></td>
</tr>
<tr>
<td> Work Experiance</td><td> : </td>
<td><select name="exp" onblur="expselect();">
<option > Select One</option>
<option selected="" value="Default"> Select One </option>
<option value="F"> Fresher </option>
<option value="E"> Experiance</option>
</select></td>
</tr>
<tr>
<td>User Name</td><td>:</td><td> <input type='txt' name='uname' id='uid'size="50" style="background-color:#abcddd; height:18px; " value=''onblur="userid_validation(5,10);"> </td>
</tr>
<tr>
<td>Password</td><td>:</td><td> <input type='password' name='pwd' id='pid' size="50" style="background-color:#abcddd; height:18px; " value=''onblur="passid_validation(7,12);"></td>
</tr>
<tr>
<td> </td>
<td> </td>
<td width="84"><input name="enter" class="btn_login" type="submit" value="Submit" onsubmit="alert('Data stored successfully');"/> <input name="cancle" class="btn_login" type="reset" value="Cancle" /></td>
</tr>
</table>
</form>
</body>
</html>
I included the external javascript file using script tag but the validations are not working.
This is my external javascript code which was saved as validation.js and i am unable to find errors in it please help me.
// After form loads focus will go to first name field.
function firstfocus()
{
var fname = document.f2.fname.focus();
return true;
}
// This function will validate First name
function fname_validation(mx,my)
{
var fname = document.f2.fname;
var fname_len = fname.value.length;
var letters = /^[A-Za-z]+$/;
if (fname_len == 0 || fname_len >= my || fname_len < mx)
{
alert("First Name should not be empty / length be between "+mx+" to "+my);
fname.focus();
return false;
if(fname.value.match(letters))
{
// Focus goes to next field i.e.Last Name
document.f2.lname.focus();
return true;
}
}
}
// This function will validate Last name
function lname_validation(mx,my)
{
var lname = document.f2.lname;
var lname_len = lname.value.length;
var letters = /^[A-Za-z]+$/;
if (lname_len == 0 || lname_len >= my || lname_len < mx)
{
alert("Last Name should not be empty / length be between "+mx+" to "+my);
lname.focus();
return false;
if(fname.value.match(letters))
{
// Focus goes to next field i.e.Phone Number
document.f2.phone.focus();
return true;
}
}
}
// This function will validate Phone Number.
function allnumeric()
{
var phone = document.f2.phone;
var numbers = /^[0-9]+$/;
if(phone.value.match(numbers))
{
// Focus goes to next field i.e. Experiance.
document.f2.exp.focus();
return true;
}
else
{
alert('Phone Number must have numeric characters only');
phone.focus();
return false;
}
}
// This function will select Experiance.
function expselect()
{
var exp = document.f2.exp;
if(exp.value == "Default")
{
alert('Select your Experiance from the list');
exp.focus();
return false;
}
else
{
// Focus goes to next field i.e. Username Code.
document.f2.uname.focus();
return true;
}
}
// This function will validate User Name.
function allLetter()
{
var uname = document.f2.uname;
var letters = /^[A-Za-z]+$/;
if(uname.value.match(letters))
{
// Focus goes to next field i.e. Password.
document.f2.pwd.focus();
return true;
}
else
{
alert('Username must have alphabet characters only');
uname.focus();
return false;
}
}
// This function will validate Password.
function passid_validation(mx,my)
{
var passid = document.registration.passid;
var passid_len = passid.value.length;
if (passid_len == 0 ||passid_len >= my || passid_len < mx)
{
alert("Password should not be empty / length be between "+mx+" to "+my);
passid.focus();
return false;
}
}
try to change <script type="javascript/text"> to <script type="text/javascript">
and double check the reference of your js file. Also, put an alert check to determine if it is really going through the firstFocus() function.
You have to reference the .js if its not in the same folder as html
EDIT
function fname_validation(mx,my)
{
is missing a closing bracket!
I changed the java script file and now i can find validations in my form...
Thanks for your help..
here i am sharing my code...
HTML code
<form name='f1' action="insert_ac.php" method="post" onSubmit="return validateForm();" >
<tr>
<td height="25" height="25" colspan="2" bgcolor="#EC6921" class="form_heading">Add User Form</td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> First Name:</td>
<td bgcolor="#FFFFFF"> <input type='text' name='fname' id='fid' size="50" style="height:18px;" value='' maxlength="100" ></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Last Name:</td>
<td bgcolor="#FFFFFF" > <input type='text' name='lname' id='lid' size="50" style=" height:18px; "value='' maxlength="100" ></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Gender:</td>
<td bgcolor="#FFFFFF" > <input type='radio' name='gend' id='m' value='M' checked>Male <input type='radio' name='gend' id='f' value='F'>Female</td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Phone Number:</td>
<td bgcolor="#FFFFFF" > <input type='number_format' name='phone' id='phno'size="50" style=" height:18px; " value=''></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt"> Work Experiance:</td>
<td bgcolor="#FFFFFF" ><select name="exp" >
<option selected="" value="Default"> Select One </option>
<option value="Fresher"> Fresher </option>
<option value="Experiance"> Experiance</option>
</select></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt">User Name:</td><td bgcolor="#FFFFFF"> <input type='txt' name='uname' id='uid'size="50" style=" height:18px; " value=''></td>
</tr>
<tr>
<td bgcolor="#FFFFFF" height="28" class="form_txt">Password:</td><td bgcolor="#FFFFFF"> <input type='password' name='pwd' id='pid' size="50" style=" height:18px; " value=''></td>
</tr>
</table>
<table align="center">
<tr>
<td ><input name="enter" class="btn_login" type="submit" value="Submit" align="center"><input name="cancle" class="btn_login" type="reset" value="Cancle" valign="right" /></td>
</tr>
</table>
</div>
</div>
</div>
</form>
</body>
</html>
Here is my java script file which is working fine....
var RE = /^.+#.+\..{3}$/;
var RE1 = /^[a-zA-Z]+$/;
var RE2 = /^[0-9]{10}$/;
var RE3 = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
function validateForm()
{
if (document.f1.fname.value == "")
{
window.alert("first name should NOT BE empty");
document.f1.fname.focus();
return false;
}
else
if (RE1.test(document.f1.fname.value) == false)
{
alert("Invalid first name\n\
");
return false;
}
else
if (document.f1.fname.value.length < 3)
{
window.alert("Firstname must have atleast Three characters");
document.f1.fname.focus();
return false;
}
else
if (document.f1.lname.value == "")
{
window.alert("Lastname should not be empty");
document.f1.lname.focus();
return false;
}
else
if (RE1.test(document.f1.lname.value) == false)
{
alert("Invalid last name");
return false;
}
else
if (document.f1.lname.value.length < 4)
{
window.alert("Lastname must have atleast four characters");
document.f1.lname.focus();
return false;
}
else
if (document.f1.lname.value == "")
{
window.alert("Last name should not be empty");
document.f1.lname.focus();
return false;
}
else
if (document.f1.phone.value == "")
{
window.alert("phne no should NOT BE empty");
document.f1.phone.focus();
return false;
} else
if (RE3.test(document.f1.phone.value) == false)
{
alert("Invalid phone number");
document.f1.phone.focus();
return false;
}
else
if (document.f1.exp.selectedIndex == 0)
{
window.alert("please select work experiance ");
return false;
}
else
if (document.f1.uname.value == "")
{
window.alert("UserName should not be empty");
document.f1.uname.focus();
return false;
}
else
if (RE1.test(document.f1.uname.value) == false)
{
window.alert("Invalid userName ");
document.f1.uname.focus();
return false;
}
else
if (document.f1.pwd.value == "")
{
window.alert("password should not be empty");
document.f1.pwd.focus();
return false;
}
else
if (document.f1.pwd.value.length < 6)
{
window.alert("password must have atleast six characters");
document.f1.pwd.focus();
return false;
}
else
{
window.alert("User has been added successfully.");
return true;
}
}
JQUERY
<script type="text/javascript" src="jquery-1.5.1.min.js"></script>
<script type="text/javascript">
$('#aggiungi').live('click', function(){
var thisRow = $(this).parent().parent();
// clone and add data
thisRow.clone(true).insertAfter(thisRow).data('is_clone',true);
$(this).val("-");
$(this).attr("id","remove");
var nextRow = thisRow.next();
nextRow.find('input:not(#aggiungi)').val("");
if (thisRow.data('is_clone')){
while(thisRow.data('is_clone')){
thisRow = thisRow.prev();
}
}else{
nextRow.children(":first").remove();
}
currRowSpan = thisRow.children(":first").attr("rowspan");
thisRow.children(":first").attr("rowspan", currRowSpan+1);
});
$('#remove').live('click', function(){
var thisRow = $(this).parent().parent(),
prevRow = thisRow.prev();
if (thisRow.data('is_clone')){
while(prevRow.data('is_clone')){
prevRow = prevRow.prev();
}
}else{
prevRow = thisRow.next()
.removeData('is_clone')
.children(":first")
.before(thisRow.children(":first"))
.end();
}
currRowSpan = prevRow.children(":first").attr("rowspan");
prevRow.children(":first").attr("rowspan", currRowSpan-1);
thisRow.remove();
});
</script>
PHP
<form action="grading.php" method="post">
<table width-"100%" id="tableRealizzazione">
<tr>
<th></th>
<th style="padding:12px;text-align:center;">Personale</th>
<th style="padding:12px;text-align:center;">Percentage</th>
<th style="padding:12px;text-align:center;">Marketing point</th>
<th style="padding:12px;text-align:center;">Add/Remove</th>
</tr>';
echo '<tr class="even">
<td></td>
<td style="padding:12px;"><input type="text" value="" id="Personale" name="Personale"></td>
<td style="padding:12px;">
<input type="text" id="from" name="from" size="5%"> -
<input type="text" id="to" name="to" size="5%"> %
</td>
<td style="padding:12px;"><input type="text" class="totaliCostiGestione" id="marketpt" name="marketpt"></td>
<td style="padding:12px;"><input type="text" name="programid" value ="34" size="10%"></td>
<td style="padding:12px;"><input type="button" value="+" id="aggiungi"/></td>';
echo '</tr>';
echo '<tr><td><input type="submit" name="submit" value="submit"></td></tr>';
echo '</table>
</form>
When I fill the values of all text boxes and click submit, it prints only the last row and the the last row with value 34 not repeating for all the rest rows.
Here is my code in Fiddle
http://jsfiddle.net/gansai/PA9JF/
That is because you have to make arrays from your form:
eg:
<input type="text" id="from" name="from[]" size="5%"> -
to clone values you have to add:
newRow = thisRow.clone(true).insertAfter(thisRow).data('is_clone',true);
$(newRow+"[name^=programid]").val($(thisRow+"[name^=programid]").val());
Like this JSFiddle
then in PHP:
foreach($_POST['marketpt'] as $num => $val){
$Personale = $_POST[$num]['Personale'];
$from = $_POST[$num]['from'];
$to = $_POST[$num]['to'];
$marketpt = $_POST[$num]['marketpt'];
$programid = $_POST[$num]['programid'];
// process variables, eg: insert in database
}
I create 2 PHP pages (test.php, getcompany.php)
in test.php page, I have a row with order details. check working DEMO here :
[DEMO] : http://delta-adv.com/test.php
As you saw in demo in first row when I select product it populate company name from database but when I click add row button then in 2nd row when I select product it change company name in top row only. below is the code for test.php
<html>
<head>
<script language="javascript" type="text/javascript">
function getXMLHTTP() { //function to return the xml http object
var xmlhttp=false;
try{
xmlhttp=new XMLHttpRequest();
}
catch(e) {
try{
xmlhttp= new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
try{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e1){
xmlhttp=false;
}
}
}
return xmlhttp;
}
function getcompany(productId) {
var strURL="getcompany.php?product="+productId;
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
document.getElementById('companydiv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
<script type="text/javascript">
function tot(elem) {
var d=document.getElementById("total").value;
var total=Number(d);
var e=document.getElementById("vat5").value;
var vat5=Number(e);
var f=document.getElementById("vat12_5").value;
var vat12_5=Number(f);
var g=document.getElementById("cash_discount").value;
var cash_discount=Number(g);
var h=(total+vat5+vat12_5)-cash_discount;
document.getElementById("grand_total").value = h;
}
var total = 0;
function getValues() {
var qty = 0;
var rate = 0;
var obj = document.getElementsByTagName("input");
for(var i=0; i<obj.length; i++){
if(obj[i].name == "qty[]"){var qty = obj[i].value;}
if(obj[i].name == "rate[]"){var rate = obj[i].value;}
if(obj[i].name == "amt[]"){
if(qty > 0 && rate > 0){obj[i].value = qty*rate;total+=(obj[i].value*1);}
else{obj[i].value = 0;total+=(obj[i].value*1);}
}
}
document.getElementById("total").value = total*1;
total=0;
}
</script>
<script type="text/javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID)
{
try
{
var table = document.getElementById(tableID);
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 <= 1)
{
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch(e)
{
alert(e);
}
getValues();
}
</script>
</head>
<body>
<form name="gr" method="post" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" onSubmit="return validateForm(this)">
<tr>
<td class="forhead" style="white-space:nowrap;"> </td>
<table width="70%" align="center" cellpadding="0" cellspacing="0" class="normal-text" border="0">
<tr>
<td width="32"></td>
<td width="126">Product</td>
<td width="149">company</td>
<td width="91" class="forhead" style="white-space:nowrap;">Qty</td>
<td width="100" class="forhead" style="white-space:nowrap;">Unit Price</td>
<td width="87" class="forhead" style="white-space:nowrap;">Total</td>
<td width="28" class="forhead" style="white-space:nowrap;"> </td>
<td width="156" class="forhead" style="white-space:nowrap;"><span class="forhead" style="white-space:nowrap;">
<span class="forhead" style="white-space:nowrap;">
<input type="button" value="Add Row" onClick="addRow('dataTable')" >
</span>
<input type="button" value="Delete Row" onClick="deleteRow('dataTable')" >
</span></td>
</tr>
</table>
<table border="0" id="dataTable" width="70%" align="center" cellpadding="0" cellspacing="0" class="normal-text">
<tr>
<td width="31" class="forhead" style="white-space:nowrap;"><input type="checkbox" name="chk[]"/> </td>
<td class="forhead" style="white-space:nowrap;" width="127">
<select name="product" onChange="getcompany(this.value)">
<option value="">Select Product</option>
<option value="1">iphone</option>
<option value="2">ipad</option>
<option value="3">Galaxy S2</option>
</select>
</td>
<td class="forhead" style="white-space:nowrap;" width="148">
<div id="companydiv"><input name="company" value="" /></div>
</td>
<td class="forhead" style="white-space:nowrap;" width="99"><input type="text" name="qty[]" onkeyup="getValues()" style="width:80px;" onBlur=""></td>
<td class="forhead" style="white-space:nowrap;" width="100"><input type="text" name="rate[]" onKeyUp="getValues()" style="width:80px;" value=""></td>
<td class="forhead" style="white-space:nowrap;" width="148"> <input type="text" name="amt[]" style="width:80px;"
onKeyUp="getValues()"></td>
<td width="8" align="right" class="forhead" style="white-space:nowrap;"> </td>
<td class="forhead" style="white-space:nowrap;" width="108"> </td>
</tr>
</table>
<table width="70%" align="center" cellpadding="0" cellspacing="0" class="normal-text" border="0">
<tr>
<td width="169" class="forhead" style="white-space:nowrap;"> </td>
<td width="600" class="forhead" style="white-space:nowrap;"> </td>
</tr>
<tr>
<td align="right"><span class="forhead" style="white-space:nowrap;">Gross Total:</span></td>
<td align="left"><span class="forhead" style="white-space:nowrap;">
<input type="text" id="total" name="total[]" style="width:80px;" value="">
</span></td>
</tr>
<tr>
<td align="center" colspan="2"><input name="Submit" type="submit" value="Save" style="text-decoration:none"/>
<input type="reset" value="Cancel" onClick="window.location.href='<?php echo $_SERVER['PHP_SELF'];?>'"></td>
</tr>
</table>
</td>
</tr>
</table>
</td>
</tr>
</form>
</body>
</html>
code for getcompany.php
<?php
$product=intval($_GET['product']);
$link = mysql_connect('localhost', 'root', ''); //Localhost configuration
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('test');
$query="SELECT * FROM tbl_company WHERE prod_ID='$product'";
$result=mysql_query($query);
$row=mysql_fetch_array($result);
?>
<input name="company" value="<?php echo $row['company_name']; ?>" />
You don't need to add special ids.
1.) First change the id to a class:
From: <div id="companydiv"><input name="company" value="" /></div>
To: <div class="companydiv"><input name="company" value="" /></div>
2.) Change the select onchange parameter to this:
From: <select name="product" onChange="getcompany(this.value)">
To: <select name="product" onChange="getcompany(this)">
3.) Replace your getcompany function with:
function getcompany(element) { // the parametername has changed
var strURL="getcompany.php?product="+element.value; // this line has changed
var req = getXMLHTTP();
if (req) {
req.onreadystatechange = function() {
if (req.readyState == 4) {
// only if "OK"
if (req.status == 200) {
// last changes here:
element.parentNode.parentNode.getElementsByClassName('companydiv')[0].innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
I see from your page that you use the same ids companyDiv for all new rows. This will be an issue.
See this line in your getCompany success method
document.getElementById('companydiv').innerHTML=req.responseText
Edit
When you add new rows, try giving an id based on the index number of this row. That way, in your <select name="product" onChange="getcompany(this.value)"> onchange method, you can exactly get the div that you are searching for
Edit 2
In your addRow method, check this line var row = table.insertRow(rowCount);
Now to change the id of this row, all you have to do is, (provided your first row has an id '1')
row.id = 'aNewId' + (parseInt(row.nextSibling.id) + 1);
ar=array("product1"=>"company1", "product2"=>"company2");
var str="";
$("#productSelectorId").change(function () {
$("select option:selected").each(function () {
str += $(this).text() + " ";
});
$("#companySelectorId").text(ar[str]);
}).change();