I hope today I'll find good solution for my case below.
Case
Actually, I have dynamic input fields and let say there field A, B and C. So, the purpose is when field A receives OnKeyUp Action then field B and C will autofill based query result from field A value.
index.php
<html>
<body>
<script type="text/javascript">
var ct = 1;
// Function Tambah Form
function new_link()
{
ct++;
var div1 = document.createElement('div');
div1.id = ct;
// Link to Delete Form
var delLink = '<div style="text-align:left"><a id="del" href="javascript:delIt('+ ct +')">Delete</a></div>';
div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;
document.getElementById('newlink').appendChild(div1);
}
// Function Delete Form
function delIt(eleId)
{
d = document;
var ele = d.getElementById(eleId);
var parentEle = d.getElementById('newlink');
parentEle.removeChild(ele);
}
function ajaxFunction(str,divId)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateChanged()
{
if(httpxml.readyState==4)
{
document.getElementById(divId).innerHTML=httpxml.responseText;
}
}
var url="cek.php";
url=url+"?txt="+str;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateChanged;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
</head>
<body>
<form name="myForm">
<a id="new" href="javascript:new_link()">ADD NEW PAYMENT</a>
<div id="newlink">
<table width="50%" border="1">
<tr>
<td><input type="text"
onkeyup="ajaxFunction(this.value,'displayDiv');" name="username" /></td>
<td>
<div id="displayDiv">
<table width="100%" border="0">
<tr>
<td><input type="text" name="curr"></td><td><input type="text" name="amount"></td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
<div id="newlinktpl" style="display:none" >
<div>
<table width="50%" border="1">
<tr>
<td><input type="text"
onkeyup="ajaxFunction(this.value,'displayDiv<?php echo ++$np;?>');" name="username" /></td>
<td>
<div id="displayDiv<?php echo $np;?>">
<table width="100%" border="0">
<tr>
<td><input type="text" name="curr"></td><td><input type="text" name="amount"></td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
</div>
cek.php
<?php
mssql_connect('localhost','sa','');
mssql_select_db('NCD');
$in=$_GET['txt'];
$msg="";
$t=mssql_query("SELECT * FROM DPaym1 WHERE (JENIS = 1) AND (DPSPAID = 0) AND (CNDPSNO = '$in')");
while($nt=mssql_fetch_array($t)){
//$msg = "$nt[CURRID]#$nt[AMOUNT]";
$curr = "$nt[CURRID]";
$amount = "$nt[AMOUNT]";
}
//echo $msg;
//echo "$curr $amount";
?>
<table width="100%" border="0">
<tr>
<td><input type="text" name="curr" value="<?php echo $curr?>"></td>
<td><input type="text" name="amount" value="<?php echo $amount?>"></td>
</tr>
</table>
Above code already success for row 1. but when I input value in row 2 (dynamic add new row) the result change field B and C in row 1 not in row 2.
Related
Last night I was trying to figure out how I can how I can dynamically enable and disable span#txtCaptchaDiv on my contact form at the very bottom, above the submit button.
So I added a new field to MySQL, called captcha where I wanted to 1 to show and 0 to hide
So if I add 1 to field captcha the following code will show on my form.php
<label for="code">Write code below > <span id="txtCaptchaDiv" style="color:#F00"></span><!-- this is where the script will place the generated code -->
<input type="hidden" id="txtCaptcha" /></label><!-- this is where the script will place a copy of the code for validation: this is a hidden field -->
<input type="text" name="txtInput" id="txtInput" size="30" />
If I add 0 to field captcha the captcha area will be blank on my form.php.
Can you guy help me out please?
here is my index.php code I currently have:
<?php
require_once("/config/database.php");
$con = mysql_connect($config["db_server"],$config["db_user"],$config["db_pass"]);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Email FORM</title>
</head>
<body>
<div style="width: 550px; text-align: center;">
<span style="filter:alpha(opacity=60); opacity:.6; padding-left: 10px;"><br />
<?php
$data = mysql_query("SELECT * FROM formrelated")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
Print " ".$info['welcomemsg'] . "";
?>
</span></div>
<form id="form1" name="form1" method="post" action="submit.php" onsubmit="return checkform(this);">
<table width="454" border="1" align="center" cellpadding="0" cellspacing="0">
<tr>
<td width="123">Name</td>
<td width="325">
<input name="name" type="text" />
</td>
</tr>
<tr>
<td height="21">Address</td>
<td><input name="adress" type="text" /></td>
</tr>
<tr>
<td height="21"> </td>
<td><input name="address2" type="text" /></td>
</tr>
<tr>
<td height="21">Email</td>
<td><input name="email" type="text" /></td>
</tr>
<tr>
<td height="21">Tel</td>
<td><input name="email" type="text" /></td>
</tr>
</table>
<!--- captcha code here--->
<center>
<table width="454" height="122" border="0" cellspacing="0" cellpadding="0" background="reCAPbg.png">
<tr>
<td height="73" colspan="2" align="center" valign="middle"><label for="code"><span id="txtCaptchaDiv" style="color:#333; font-size:18px;"></span><!-- this is where the script will place the generated code -->
<input type="hidden" id="txtCaptcha" /></label></td>
<td width="136" rowspan="2"> </td>
</tr>
<tr>
<td width="145"> type the code here:</td>
<td width="173" height="47" align="center"><input type="text" name="txtInput" id="txtInput" size="20" /></td>
</tr>
</table>
</center>
<!--- captcha code ends here--->
<input name="Submit" type="button" value="submit" />
</form>
<script type="text/javascript">
//Generates the captcha function
var a = Math.ceil(Math.random() * 9)+ '';
var b = Math.ceil(Math.random() * 9)+ '';
var c = Math.ceil(Math.random() * 9)+ '';
var d = Math.ceil(Math.random() * 9)+ '';
var e = Math.ceil(Math.random() * 9)+ '';
var code = a + b + c + d + e;
document.getElementById("txtCaptcha").value = code;
document.getElementById("txtCaptchaDiv").innerHTML = code;
</script>
<script type="text/javascript">
function checkform(theform){
var why = "";
if(theform.txtInput.value == ""){
why += "- Security code should not be empty.\n";
}
if(theform.txtInput.value != ""){
if(ValidCaptcha(theform.txtInput.value) == false){
why += "- Security code did not match.\n";
}
}
if(why != ""){
alert(why);
return false;
}
}
// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2){
return true;
}else{
return false;
}
}
// Remove the spaces from the entered and generated code
function removeSpaces(string){
return string.split(' ').join('');
}
</script>
</body>
</html>
This will work for you... enjoy!
<?PHP
$query = mysql_query("SELECT captcha FROM formrelated WHERE id = '1'");
while ($row = mysql_fetch_assoc($query)) {
$captchathis = $row['captcha'];
if ($captchathis == "1") {
echo "YOUR HTML CODE HERE";
}
else {
echo "BLANK";
}
}
?>
Try it like this
<?PHP
if($mysqlResult['captcha'] === 1)
{
echo $myHtml;
}
?>
Where $mysqlResult is an array with the result from the query, $mysqlResult['captcha']is the value of the row captcha from your query and $myHtml is that HTML code you just showed on your answer.
Good luck! ;)
Reffer to
http://php.net/manual/en/
EDIT:
http://www.php.net/manual/en/language.types.array.php ( Array type on the manual )
http://www.php.net/manual/en/control-structures.if.php ( If control structure on the manual )
http://www.php.net/manual/en/ref.mysql.php ( MySQL native functions. deprecated. Preffer MySQLi )
http://www.php.net/manual/en/book.mysqli.php ( MySQLi extension )
http://www.php.net/manual/en/book.pdo.php ( PDO native php class )
Another answer to explain the basic construct of IF logic.
Suppose i have some condition i want to meet to do something; in this case, the following logic
SHOW my form with the basic inputs
IF condition 'captcha = 1' is met, SHOW input2 (captcha)
SHOW rest of the HTML
it would be like this in PHP
<?PHP
echo $myFormWithBasicInputs;
if($captcha === 1)
{
echo $input2;
}
echo $restOfHTML;
?>
In your case, $myFormWithBasicInput and $restOfHTML is already outputed as HTML. All you want to do is inject an PHP code in it to check if some condition is matched. It will be like this
<html>
<!-- MY FORM WITH BASIC INPUTS -->
<?PHP
$captcha = $mySQLresult['captchaRow'];
if($captcha === 1)
{
?>
<!-- CAPTCHA INPUT HERE -->
<?PHP
}
?>
<!-- REST OF HTML -->
</html>
be aware that this is an workaround with example code.
<?PHP
$mysql_query = "SELECT captcha FROM formrelated";
$captcha = $mySQLresult['captchaRow'];
if($captcha === 1)
{
?>
<!--- CODE---->
<table width="454" height="122" border="0" cellspacing="0" cellpadding="0" background="reCAPbg.png">
<tr>
<td height="73" colspan="2" align="center" valign="middle"><label for="code"><span id="txtCaptchaDiv" style="color:#333; font-size:18px;"></span><!-- this is where the script will place the generated code -->
<input type="hidden" id="txtCaptcha" /></label></td>
<td width="136" rowspan="2"> </td>
</tr>
<tr>
<td width="145"> type the code here:</td>
<td width="173" height="47" align="center"><input type="text" name="txtInput" id="txtInput" size="20" /></td>
</tr>
</table>
<?PHP
}
?>
<!-- REST OF HTML -->
I have this html form:
<form method="post">
<input type="radio" name="news" id="new" value="nuova" onchange="newstype(this.id);">Nuova News
<input type="radio" name="news" id="mod" value="modifica" onchange="newstype(this.id);">Modifica News
<select name="news" id="modifica" style="display:none" onchange="shownews(this.value)">
<?php
include "../flock/sql.php";
$connection = new mysqli($host, $user, $pw, $db) or die("Impossibile connettersi");
$querylistanews = "SELECT * FROM NEWS ORDER BY id DESC";
$listanews = $connection->query($querylistanews);
print '<option>Seleziona una news...</option>';
while ($newsdamodificare = $listanews->fetch_object()) {
print '<option value="'.$newsdamodificare->id.'">'.$newsdamodificare->data." - ".$newsdamodificare->title.'</option>';
}
$listanews->close();
$connection->close;
?>
</select>
</form>
this javascript:
function newstype(param) {
if(param == 'new') {
document.getElementById('crea').style.display = 'inline';
document.getElementById('modifica').style.display = 'none';
document.getElementById('newsdamodificare').style.display = 'none';
} else {
if(param == 'mod') {
document.getElementById('crea').style.display = 'none';
document.getElementById('modifica').style.display = 'inline';
document.getElementById('newsdamodificare').style.display = 'inline';
}
}
}
function shownews(str) {
if (str=="") {
document.getElementById("newsdamodificare").innerHTML="";
return;
}
if (window.XMLHttpRequest) { // codice per IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // codice per IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("newsdamodificare").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","modifica.php?news="+str,true);
xmlhttp.send();
}
and this php:
<head>
<script type="text/javascript" src="../editor/ckeditor.js"></script>
<script type="text/javascript" src="/js/charscounter.js"></script>
</head>
<?php
$news=$_GET["news"];
include "../flock/sql.php";
$connection = new mysqli($host, $user, $pw, $db) or
die('Impossibile connettersi al database: ' . mysql_error());
$newsdaldatabase="SELECT * FROM NEWS WHERE id = '".$news."'";
$result = $connection->query($newsdaldatabase);
$count = mysqli_num_rows($result);
if($count==1){
while($dati = mysqli_fetch_array($result)) {
$id = $dati['id'];
$data = $dati['data'];
$title = $dati['title'];
$body = $dati['body'];
}
} else {
die('Errore del sistema. PiĆ¹ di una news selezionate: ' . mysql_error());
}
mysqli_close($connection);
?>
<div class="normal" id="modifica">
<table style="width:100%;height:100%;">
<tr>
<td colspan="3" border="0">
<strong class="confirm">Modifica news</strong>
</td>
</tr>
<tr>
<td width="107" align="right">
<strong>Data</strong>
</td>
<td colspan="2">
<form name="modificanews" method="post" action="italiano.php?modifica=yes">
<input name="idmodificanews" type="text" style="display:none" value="<?php echo $id ?>">
<input name="datanewsmodificata" type="text" maxlength="10" size="8" value="<?php echo $data ?>"> gg.mm.aaaa
</td>
</tr>
<tr>
<td align="right">
<strong>Titolo</strong>
</td>
<td width="360">
<input name="modificatitolo" type="text" maxlength="50" size="50" value="<?php echo $title ?>" onKeyPress="return taLimit(this)" onKeyUp="return taCount(this,'myCounter')">
</td>
<td width="522">
<b><span id=myCounter>50</span></b> caratteri rimanenti per il titolo</font>
</td>
</tr>
<tr>
<td colspan="3">
<textarea name="modificatesto"><?php echo $body ?></textarea>
<script>
CKEDITOR.replace('modificatesto');
</script>
</td>
</tr>
All is working quite well, except one thing:
when I select the news to edit, the content is from the server is correcly posted on the php, but on the HTML the scripts in the php (CKEDITOR and Char Cunter) are not active.
So, on my HTML, were the user will edit the news, i get only a simple textarea instead of the CKEDITOR, etc.
Is there a way to fix that? Can you help me somehow?
Thank you!
EDIT: I solved by myselft the problem. See solution as answer.
For those who have the same question:
I solved my problem in the following way: on javascript add a new row:
document.getElementById("newsdamodificare").action=CKEDITOR.replace('modificatesto');
between this 2 lines:
document.getElementById("newsdamodificare").innerHTML=xmlhttp.responseText;
NEW LINE TO INSERT HERE
}
And remove from the php these rows:
<script>
CKEDITOR.replace('modificatesto');
</script>
Hope this helps!
You're trying to select your textarea by it's name, but CKEDITOR.replace('modificatesto'); is looking for an ID.
Try
<textarea id="modificatesto"><?php echo $body ?></textarea>
<script>
CKEDITOR.replace('modificatesto');
</script>
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
}
Hi everyone im new to php and would like to know how if it is possible determine what to insert into parent window textarea from child window using radio buttons in child window. How should I go about doing it? I would much appreciate it if anyone could provide some help on this. Below is the code. Thanks.
Parent Window:
<head>
<script type='text/javascript'>
window.onload = function()
{
document.getElementById('b1').onclick = openChild;
}
function openChild()
{
this.disabled = false;
xWinOpen('retrievemath.php');
}
var xChildWindow = null;
function xWinOpen(sUrl)
{
// Modify 'features' to suit your needs:
var features = "left=100,top=100,width=400,height=400,location=0,menubar=0," +
"resizable=1,scrollbars=1,status=0,toolbar=0";
if (xChildWindow && !xChildWindow.closed) {xChildWindow.location.href = sUrl;}
else {xChildWindow = window.open(sUrl, "myWinName", features);}
xChildWindow.focus();
return false;
}
</script>
<script src="ckeditor/ckeditor.js"></script>
</head>
<body>
<textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10" ></textarea>
<form>
<input type="button" id ="b1" onClick="myPopup2()" value="POP2!">
</form>
<p onClick="myPopup2()">CLICK ME TOO!</p>
</body>
Child Window:
<?php
include ('database_connection.php');
$dbConn = mysql_connect('localhost', 'root', '')
or trigger_error(mysql_error(), E_USER_ERROR);
// select the database for use
mysql_select_db('test', $dbConn);
$query_retrieve_expression = "SELECT * FROM math";
$queryResource = mysql_query($query_retrieve_expression, $dbConn) or die(mysql_error());
?>
<head>
<script type='text/javascript'>
window.onload = function()
{
document.getElementById('f1').onsubmit = sendToParent;
}
function sendToParent()
{
if (window.opener) {
var cta = document.getElementById('<?php echo $row['mathID']?>');
var pta = window.opener.document.getElementById('editor1');
pta.value = cta.value;
window.opener.focus();
}
return false;
}
</script>
</head>
<body>
<form action="retrievemath.php" method="post" id="f1">
<table class="hovertable">
<tr>
<th>Insert ?</th><th>Expression Name</th><th>Math Expression</th>
</tr>
<?php
while($row = mysql_fetch_assoc($queryResource))
{
?>
<tr>
<td><input type="radio" name="insert" id="<?php echo $row['mathID']?>" value="<?php echo $row['expressionname']?>" /> </td>
<td><?php echo $row['expressionname']; ?></td>
<td><?php echo $row['mathexpression']; ?></td>
</tr>
<?php
}
?>
</table>
<div class="submit">
<input type="submit" value="Insert" />
</div>
</form>
</body>
You can get value for textarea and passed in url like this
Latest function
function sendToParent()
{
var cta='';
var radio=document.getElementsByName("insert");
for(var i=0;i<radio.length;i++)
{
cta+=radio[i].value;
}
var pta = var pta = window.opener.document.getElementById("editor1");
pta.value = cta;
self.close();
}
You can get value of textarea in child window like this
echo $_GET['data'];
Child window code
<head>
<script type='text/javascript'>
function sendToParent()
{
var cta='';
var radio=document.getElementsByName("insert");
for(var i=0;i<radio.length;i++)
{
cta+=radio[i].value;
}
var pta =var pta = window.opener.document.getElementById("editor1");
pta.value = cta;
self.close();
}
</script>
</head>
<body>
<form action="retrievemath.php" method="post" id="f1">
<table class="hovertable">
<tr>
<th>Insert ?</th><th>Expression Name</th><th>Math Expression</th>
</tr>
<tr onmouseover="this.style.backgroundColor='#ffff66';" onmouseout="this.style.backgroundColor='#d4e3e5';">
</tr>
<?php
while($row = mysql_fetch_assoc($queryResource))
{
?>
<tr>
<td><input type="radio" name="insert" id="<?php echo $row['mathID']?>" value="<?php echo $row['expressionname']?>" /> </td>
<td><?php echo $row['expressionname']; ?></td>
<td><?php echo $row['mathexpression']; ?></td>
</tr>
<?php
}
?>
</table>
<div class="submit">
<input type="button" value="Insert" onclick="sendToParent();" />
</div>
</form>
</body>
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();