javascript - pass selected value from popup window to parent window input box - javascript

I am building an order form with PHP and MySQL.
The PHP Form has an input box where the user types in a product code. In the event that the user does not know the product code, I want them to click on an image or button next to the input box, which opens a popup with a list of all product codes. they can then click on the product they want and the product code is passed from the popup to the input box on that table row.
I have the code of my page below and the image of the page it creates so you can get a feel for what I am wanting to acheive.
parent page
<table border=0 id="hor-minimalist-a">
<tr>
<th valign=bottom>KVI</th>
<th valign=bottom>PACK CODE</th>
<th valign=bottom width=250>DESCRIPTION</th>
<th valign=bottom width=40>WHSE</th>
<th valign=bottom width=25>SU</th>
</tr>
<tr id="r1">
<td>
<input type=checkbox name=kvi1 id=kvi1 value=1>
</td>
<td>
<input size=10 type=number id=sku1 name=sku1 onchange="showUser(1, this.value)">
<input type="button" name="choice" onClick="window.open('sku.php','popuppage','width=400,toolbar=1,resizable=1,scrollbars=yes,height=400,top=100,left=100');" value="?">
</td>
<td>
<div align="left" id="txtHint1"> </div>
</td>
<td>
<div align="left" id="whse1"> </div>
</td>
<td>
<div align="left" id="su1"> </div>
</td>
</tr>
<tr id="r2">
<td>
<input type=checkbox name=kvi2 id=kvi2 value=2>
</td>
<td>
<input size=10 type=number id=sku2 name=sku2 onchange="showUser(2, this.value)"><img src=q.png>
</td>
<td>
<div align="left" id="txtHint2"> </div>
</td>
<td>
<div align="left" id="whse2"> </div>
</td>
<td valign=bottom>
<div align="left" id="su2"> </div>
</td>
</tr>
<tr id="r3">
<td>
<input type=checkbox name=kvi3 id=kvi3 value=3>
</td>
<td>
<input size=10 type=number id=sku3 name=sku3 onchange="showUser(3, this.value)"><img src=q.png>
</td>
<td>
<div align="left" id="txtHint3"> </div>
</td>
<td>
<div align="left" id="whse3"> </div>
</td>
<td>
<div align="left" id="su3"> </div>
</td>
</tr>
<tr id="r4">
<td>
<input type=checkbox name=kvi4 id=kvi4 value=4>
</td>
<td>
<input size=10 type=number id=sku4 name=sku4 onchange="showUser(4, this.value)"><img src=q.png>
</td>
<td>
<div align="left" id="txtHint4"> </div>
</td>
<td>
<div align="left" id="whse4"> </div>
</td>
<td>
<div align="left" id="su4"> </div>
</td>
</tr>
</table>
</form>
the popup page code and image is below:
<?
$con = mysql_connect('localhost', 'dbuser', 'dbpass');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("databasename", $con);
$skusql="select packcode,category,description,grouping,packconfig,sellingunits,eottpoints from skudata order by category, packcode";
$resultsku=mysql_query($skusql);
?>
<SCRIPT LANGUAGE="JavaScript">
<!-- Begin
function sendValue (s){
var selvalue = s.value;
window.opener.document.getElementById('details').value = selvalue;
window.close();
}
// End -->
</script>
<form name="selectform">
<table border=0 width=1000 id="hor-minimalist-a">
<tr>
<th>Pack Code</th>
<th> </th>
<th>Category</th>
<th>Product Description</th>
<th>Grouping</th>
<th>Pack Config</th>
<th>SU</th>
<th>Points</th>
</tr>
<?php
while($rows=mysql_fetch_array($resultsku)){
?>
<tr>
<td><input name=details size=5 value="<?php echo $rows['packcode']; ?>"></td>
<td><input type=button value="Select" onClick="sendValue(this.form.details);"</td>
<td><?php echo $rows['category']; ?></td>
<td><center><?php echo $rows['description']; ?></td>
<td><center><?php echo $rows['grouping']; ?></td>
<td><center><?php echo $rows['packconfig']; ?></td>
<td><center><?php echo $rows['sellingunits']; ?></td>
<td><center><?php echo $rows['eottpoints']; ?></td>
</tr>
<?php
}
?>
</table>
I am trying to pass the value of the product code from the selected popup window row, to the parent window input box for 'pack code'
I was trying to adapt a script I came across but am not pulling it off. Any help appreciated as always!
Regards,
Ryan
UPDATE TO QUESTION:
PARENT PAGE:
<html>
<head>
<title>Unilever Sales Portal</title>
<style>
#import url("style.css");
</style>
<script type="text/javascript">
function showUser(userNumber, str)
{
if (str=="")
{
document.getElementById("txtHint" + userNumber).innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//document.getElementById("txtHint" + userNumber).innerHTML=xmlhttp.responseText;
var responseText = xmlhttp.responseText;
var description = responseText;
var warehouse = "";
var sellingUnits = "";
if (responseText.indexOf("NOT A VALID") == -1)
{
description = responseText.substring(12, responseText.indexOf(",Warehouse:"));
warehouse = responseText.substring(responseText.indexOf(",Warehouse:")+11, responseText.indexOf(",SellingUnits:"));
sellingUnits = responseText.substring(responseText.indexOf(",SellingUnits:")+15);
}
document.getElementById("whse" + userNumber).innerHTML = warehouse;
document.getElementById("txtHint" + userNumber).innerHTML = description;
document.getElementById("su" + userNumber).innerHTML = sellingUnits;
}
}
xmlhttp.open("GET","getdata1.php?q="+str,true);
xmlhttp.send();
}
</script>
<script type="text/javascript">
function selectValue(id)
{
// open popup window and pass field id
window.open('sku.php?id=' + encodeURIComponent(id),'popuppage',
'width=400,toolbar=1,resizable=1,scrollbars=yes,height=400,top=100,left=100');
}
function updateValue(id, value)
{
// this gets called from the popup window and updates the field with a new value
document.getElementById(id).value = value;
}
</script>
</head>
SKU.PHP
<?
$con = mysql_connect('localhost', 'dbuser', 'dbpass');
if (!$con)
{
die('Could not connect to server: ' . mysql_error());
}
$db=mysql_select_db("dbname", $con);
if (!$db)
{
die('Could not connect to DB: ' . mysql_error());
}
$sql="select packcode,category,description,grouping,packconfig,sellingunits,eottpoints from skudata order by category, packcode";
$result=mysql_query($sql);
?>
<script type="text/javascript">
function sendValue(value)
{
var parentId = <?php echo json_encode($_GET['id']); ?>;
window.opener.updateValue(parentId, value);
window.close();
}
</script>
<form name="selectform">
<table border=0 width=1000 id="hor-minimalist-a">
<tr>
<th>Pack Code</th>
<th> </th>
<th>Category</th>
<th>Product Description</th>
<th>Grouping</th>
<th>Pack Config</th>
<th>SU</th>
<th>Points</th>
</tr>
<?php
while($rows=mysql_fetch_array($result)){
?>
<tr>
<td><input name=details size=5 value="<?php echo $rows['packcode']; ?>"></td>
<td><input type=button value="Select" onClick="sendValue(this.form.details);"</td>
<td><?php echo $rows['category']; ?></td>
<td><center><?php echo $rows['description']; ?></td>
<td><center><?php echo $rows['grouping']; ?></td>
<td><center><?php echo $rows['packconfig']; ?></td>
<td><center><?php echo $rows['sellingunits']; ?></td>
<td><center><?php echo $rows['eottpoints']; ?></td>
</tr>
<?php
}
?>
</table>
Here is the images to show the workings.
parent page:
Popup Page:
Parent Page after popup
Thanks again for the help.
Regards,
Ryan

If you want a popup window rather than a <div />, I would suggest the following approach.
In your parent page, you call a small helper method to show the popup window:
<input type="button" name="choice" onClick="selectValue('sku1')" value="?">
Add the following JS methods:
function selectValue(id)
{
// open popup window and pass field id
window.open('sku.php?id=' + encodeURIComponent(id),'popuppage',
'width=400,toolbar=1,resizable=1,scrollbars=yes,height=400,top=100,left=100');
}
function updateValue(id, value)
{
// this gets called from the popup window and updates the field with a new value
document.getElementById(id).value = value;
}
Your sku.php receives the selected field via $_GET['id'] and uses it to construct the parent callback function:
?>
<script type="text/javascript">
function sendValue(value)
{
var parentId = <?php echo json_encode($_GET['id']); ?>;
window.opener.updateValue(parentId, value);
window.close();
}
</script>
For each row in your popup, change code to this:
<td><input type=button value="Select" onClick="sendValue('<?php echo $rows['packcode']; ?>')" /></td>
Following this approach, the popup window doesn't need to know how to update fields in the parent form.

(parent window)
<html>
<script language="javascript">
function openWindow() {
window.open("target.html","_blank","height=200,width=400, status=yes,toolbar=no,menubar=no,location=no");
}
</script>
<body>
<form name=frm>
<input id=text1 type=text>
<input type=button onclick="javascript:openWindow()" value="Open window..">
</form>
</body>
</html>
(child window)
<html>
<script language="javascript">
function changeParent() {
window.opener.document.getElementById('text1').value="Value changed..";
window.close();
}
</script>
<body>
<form>
<input type=button onclick="javascript:changeParent()" value="Change opener's textbox's value..">
</form>
</body>
</html>
http://www.codehappiness.com/post/access-parent-window-from-child-window-or-access-child-window-from-parent-window-using-javascript.aspx

My approach: use a div instead of a pop-up window.
See it working in the jsfiddle here: http://jsfiddle.net/6RE7w/2/
Or save the code below as test.html and try it locally.
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function(){
$('.btnChoice').on('click', function(){
$('#divChoices').show()
thefield = $(this).prev()
$('.btnselect').on('click', function(){
theselected = $(this).prev()
thefield.val( theselected.val() )
$('#divChoices').hide()
})
})
$('#divChoices').css({
'border':'2px solid red',
'position':'fixed',
'top':'100',
'left':'200',
'display':'none'
})
});
</script>
</head>
<body>
<div class="divform">
<input type="checkbox" name="kvi1" id="kvi1" value="1">
<label>Field 1: </label>
<input size="10" type="number" id="sku1" name="sku1">
<button id="choice1" class="btnChoice">?</button>
<br>
<input type="checkbox" name="kvi2" id="kvi2" value="2">
<label>Field 2: </label>
<input size="10" type="number" id="sku2" name="sku2">
<button id="choice2" class="btnChoice">?</button>
</div>
<div id="divChoices">
Select something:
<br>
<input size="10" type="number" id="ch1" name="ch1" value="11">
<button id="btnsel1" class="btnselect">Select</button>
<label for="ch1">bla bla bla</label>
<br>
<input size="10" type="number" id="ch2" name="ch2" value="22">
<button id="btnsel2" class="btnselect">Select</button>
<label for="ch2">ble ble ble</label>
</div>
</body>
</html>
clean and simple.

From your code
<input type=button value="Select" onClick="sendValue(this.form.details);"
Im not sure that your this.form.details valid or not.
IF it's valid, have a look in window.opener.document.getElementById('details').value = selvalue;
I can't found an input's id contain details I'm just found only id=sku1 (recommend you to add " like id="sku1").
And from your id it's hardcode. Let's see how to do with dynamic when a child has callback to update some textbox on the parent
Take a look at here.
First page.
<html>
<head>
<script>
function callFromDialog(id,data){ //for callback from the dialog
document.getElementById(id).value = data;
// do some thing other if you want
}
function choose(id){
var URL = "secondPage.html?id=" + id + "&dummy=avoid#";
window.open(URL,"mywindow","menubar=1,resizable=1,width=350,height=250")
}
</script>
</head>
<body>
<input id="tbFirst" type="text" /> <button onclick="choose('tbFirst')">choose</button>
<input id="tbSecond" type="text" /> <button onclick="choose('tbSecond')">choose</button>
</body>
</html>
Look in function choose I'm sent an id of textbox to the popup window (don't forget to add dummy data at last of URL param like &dummy=avoid#)
Popup Page
<html>
<head>
<script>
function goSelect(data){
var idFromCallPage = getUrlVars()["id"];
window.opener.callFromDialog(idFromCallPage,data); //or use //window.opener.document.getElementById(idFromCallPage).value = data;
window.close();
}
function getUrlVars(){
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
</script>
</head>
<body>
Car <br />
Food <br />
</body>
</html>
I have add function getUrlVars for get URL param that the parent has pass to child.
Okay, when select data in the popup, for this case it's will call function goSelect
In that function will get URL param to sent back.
And when you need to sent back to the parent just use window.opener and the name of function like window.opener.callFromDialog
By fully is window.opener.callFromDialog(idFromCallPage,data);
Or if you want to use window.opener.document.getElementById(idFromCallPage).value = data; It's ok too.

use:
opener.document.<id of document>.innerHTML = xmlhttp.responseText;

Related

Email is send on loading of the app script, but email needed to be send onclick

I have created an app script in which email can be send to the login user and to the email Ids which are mentioned in spreadsheet. The email is send to the active user and to all the mentioned email Ids.
However I want email to be send to login user (which is done) and to the specified email Id when selected via app script.
But the mail is send to all the mentioned email IDs in spreadsheet when the app script is getting loaded, whereas the mail should be send onclick, which is not working.
function doGet() {
return HtmlService
.createTemplateFromFile('index')
.evaluate();
}
function getData() {
return SpreadsheetApp
.openById('SS ID')
.getDataRange()
.getValues();
}
function sendMessage(ManagerID,proNo,proName){
var email=Session.getActiveUser().getEmail();
var eId=ManagerID;
var subject="Feedback form initiated" ;
var message="Feedback form initiated by "+eId;
var message2="To fill the feedback form please follow the url: ";
var url="googleform's ID";
var subject2="Feedback Form";
MailApp.sendEmail(eId, subject, message);
MailApp.sendEmail(email,subject2,message2+url);
}
//index.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body onload="document.getElementById('one').style.visibility='hidden'">
<div id="initiateFb">
<form>
<? var data = getData(); ?>
<table border='1px solid black'>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<? for (var j = 0; j < data[i].length; j++) { ?>
<td><?= data[i][j] ?></td>
<?if(j==(data[i].length-1)&&i!=0) { ?>
<td><input type="submit" name="submit" value="Initiate"
onclick="document.getElementById('initiateFb').style.display = 'none';
document.getElementById('one').style.visibility='visible';
<?var ManagerID=data[i][6];?> <?var proNo=data[i][1];?> <?var proName=data[i][2];?>
document.getElementById('div1').innerHTML='<?=data[i][1] ?>';
document.getElementById('div2').innerHTML='<?=data[i][2] ?>';
document.getElementById('div3').innerHTML='<?=data[i][3] ?>';
document.getElementById('div4').innerHTML='<?=data[i][4] ?>';
document.getElementById('div5').innerHTML='<?=data[i][5] ?>';
document.getElementById('div6').innerHTML='<?=data[i][6] ?>';
document.getElementById('div7').innerHTML='<?=data[i][7] ?>';
document.getElementById('div8').innerHTML='<?=data[i][8] ?>';
document.getElementById('div9').innerHTML='<?=data[i][9] ?>';
return false;"/>
</td>
<? } ?>
<? } ?>
</tr>
<? } ?>
</table>
</form>
</div>
<div id="one">
<form>
<table>
<tr>
<td>ca :</td>
<td id="div1"></td>
</tr>
<tr>
<td>cb :</td>
<td id="div2"></td>
</tr>
<tr>
<td>cc:</td>
<td id="div3"></td>
</tr>
<tr>
<td>cd :</td>
<td id="div4"></td>
</tr>
<tr>
<td>ce:</td>
<td id="div5"></td>
</tr>
<tr>
<td>cf:</td>
<td id="div6"></td>
</tr>
<tr>
<td>cg :</td>
<td id="div7"></td>
</tr>
<tr>
<td>ch :</td>
<td id="div8"></td>
</tr>
<tr>
<td>ci:</td>
<td id="div9"></td>
</tr>
</table>
<input type="submit" name="submit" value="Initiate Feedback" onclick="<?sendMessage(ManagerID,proNo,proName);?>"/>
</form>
</div>
</body>
</html>
I have attached my code.
arturro is correcct in the question comment. To make an asynchronous call you must use
google.script.run.sendMessage(ManagerID,proNo,proName)
However make note that
<input type="submit" name="submit" value="Initiate Feedback" onclick="google.script.run.sendMessage(ManagerID,proNo,proName)"
will not work because you are doing that within the HTML body. You are better of using a javascript code between <script></script> which would fetch the variables you need and then you can use the google.script.run in order to send out the email.
So you would then have
<script>
function sender() {
var ManagerID, proNo, proName;
//use Document.getElementById in order to populate the variables with
//what you need from the form
google.script.run.sendMessage(ManagerID, proNo, proName);
}
</script>
<input type="submit" name="submit" value="Initiate Feedback" onclick="sender()">
The <script></script> part is supposed to be in your index.html as it is a client side script that will handle the calling of the server side script
I have done something similar and it works fine.

How to pass getElementById to PHP that can store data to database

I have write a coding that it can generate the total quantity automatically base on the gender.I write it by using a javascript. But I dont know how to get that data to be store into the database by using php All the coding is in one page.
Here is my code
<script type = "text/javascript">
function updateTotal() {
var genderPart=0;
var totalPart =0;
function checkGender(){
if(document.getElementById('gender').value=='GIRL'){
genderPart+=1;
}
if(document.getElementById('gender').value=='BOY'){
genderPart+=2;
}
}//end of checking gender part
checkGender();
var totalPart= genderPart;
document.getElementById('totalPart').innerHTML = totalPart;
}//end of my main total function
</script>
<form action="" method="post" name="nomineeform">
<table align="center" width="800" border="2" >
<tr>
<td align="right"><b>Gender :</b></td>
<td><select name="gender" id="gender" onchange="updateTotal()">
<option selected="selected" value="">--Choose--</option>
<option value="GIRL" >GIRL</option>
<option value="BOY" >BOY</option>
</select></td>
</tr>
<tr>
<td align="right"><b>Type of Animal :</b></td>
<td><select name="animal" id="animal" onchange="updateTotal()">
<option selected="selected" value="">--Jenis Haiwan--</option>
<?php
$get_animal = "select * from animal";
$run_animal = pg_query($get_animal);
while ($row_animal=pg_fetch_array($run_animal))
{
$animal_id = $row_animal['animal_id'];
$animal_name = $row_animal['typeanimal'];
echo "<option value='$animal_id'>$animal_name</option>";
}
?>
</select></td>
</tr>
<tr>
<td align="right"><b>Quantity :</b></td>
<td><input type="text" name="quantity" size="60" value = "<?php echo $_GET['totalPart'];?>" required="required"/></td>
</tr>
<tr></tr>
<tr align="center">
<td colspan="8"><input type="submit" name="nominee" class="btn btn-info" value=" TERUSKAN " onclick="return val();"/></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['nominee']))
{
$connection = pg_connect("user = postgres password = syafiqah26 port = 5433 dbname = bengkel2 host = localhost");
$name = pg_escape_string($_POST['name']);
$gender =pg_escape_string($_POST['gender']);
$age= pg_escape_string($_POST['age']);
$cust_id= pg_escape_string($_POST['hidden']);
$animal= pg_escape_string($_POST['animal']);
$quantity= pg_escape_string($_POST['quantity']);
$query = "INSERT INTO nominee(name,age,gender,cust_id,animal,quantity)
VALUES('$name','$age','$gender','$cust_id','$animal','$quantity')";
$result = pg_query($connection,$query);
}
You need to do 2 things:
Give the INPUT an ID.
Update the INPUT using a different method (document.getElementById("totalPart").setAttribute("value", totalPart);)
Source: Javascript set value of an input field
I made notes in the code using "<-- I CHANGED THIS". It may not be obvious because of long lines but you have to remove those to test.
<script type = "text/javascript">
function updateTotal() {
var genderPart=0;
var totalPart =0;
function checkGender(){
if(document.getElementById('gender').value=='GIRL'){
genderPart+=1;
}
if(document.getElementById('gender').value=='BOY'){
genderPart+=2;
}
}//end of checking gender part
checkGender();
totalPart = genderPart;
document.getElementById("totalPart").setAttribute("value", totalPart); <-- I CHANGED THIS
}//end of my main total function
</script>
<form action="" method="post" name="nomineeform">
<table align="center" width="800" border="2" >
<tr>
<td align="right"><b>Gender :</b></td>
<td><select name="gender" id="gender" onchange="updateTotal()">
<option selected="selected" value="">--Choose--</option>
<option value="GIRL" >GIRL</option>
<option value="BOY" >BOY</option>
</select></td>
</tr>
<tr>
<td align="right"><b>Type of Animal :</b></td>
<td><select name="animal" id="animal" onchange="updateTotal()">
<option selected="selected" value="">--Jenis Haiwan--</option>
<?php
$get_animal = "select * from animal";
$run_animal = pg_query($get_animal);
while ($row_animal=pg_fetch_array($run_animal))
{
$animal_id = $row_animal['animal_id'];
$animal_name = $row_animal['typeanimal'];
echo "<option value='$animal_id'>$animal_name</option>";
}
?>
</select></td>
</tr>
<tr>
<td align="right"><b>Quantity :</b></td>
<td><input type="text" name="quantity" size="60" id="totalPart" value = "0" required="required"/></td> <-- I CHANGED THIS
</tr>
<tr></tr>
<tr align="center">
<td colspan="8"><input type="submit" name="nominee" class="btn btn-info" value=" TERUSKAN " onclick="return val();"/></td>
</tr>
</table>
</form>
<?php
if(isset($_POST['nominee']))
{
$connection = pg_connect("user = postgres password = syafiqah26 port = 5433 dbname = bengkel2 host = localhost");
$name = pg_escape_string($_POST['name']);
$gender =pg_escape_string($_POST['gender']);
$age= pg_escape_string($_POST['age']);
$cust_id= pg_escape_string($_POST['hidden']);
$animal= pg_escape_string($_POST['animal']);
$quantity= pg_escape_string($_POST['quantity']);
$query = "INSERT INTO nominee(name,age,gender,cust_id,animal,quantity)
VALUES('$name','$age','$gender','$cust_id','$animal','$quantity')";
$result = pg_query($connection,$query);
}
The way to do what you're trying to do is via AJAX. The idea being that you can take all the stuff you just did in JavaScript and call a PHP page to send the results without having to actually render the page.
And example how how this works:
checkGender();
var totalPart= genderPart;
sendTotalPart(totalPart);
function sendTotalPart(totalPart) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
//document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "YourPHPPage.php?totalPart="+ totalPart, true);
xhttp.send();
}
By the comments on OP:
1º You want to display the information of totalPart.
For this you just need to create an input in your form, and make it read-only to forbid user edits.
<tr>
<td align="right"><b>Total Parts:</b></td>
<td><input id="totalPart" type="text" name="totalPart" size="60" readonly/></td>
</tr>
You need to set the ID attribute to it, so you can set its value through document.getElementById like this:
var totalPart= genderPart;
document.getElementById('totalPart').value = totalPart;
see this post: Set the value of an input field
2º You want to send the information when form is submitted.
There's nothing much to do here, since the totalPart is already an input of your form, it will be sent to PHP naturally when the form is submitted.

add text field dynamically in to a html table

$(document).ready(function() {
var maxField = 10;
var addButton = $('.add_button');
var wrapper = $('.field_wrapper');
var fieldHTML = '<div><input type="text" name="Tape_Code[]" value=""/>delete</div>';
var x = 1;
$(addButton).click(function() {
if (x < maxField) {
x++;
$(wrapper).append(fieldHTML);
}
});
$(wrapper).on('click', '.remove_button', function(e) {
e.preventDefault();
$(this).parent('div').remove();
x--;
});
});
<?php
include_once 'dpconnect.php';
$que=mysqli_query($MySQLiconn,"select Backup_Name from admin_backup_list ");
if(isset($_POST['confirm'])) {
$Date=date('d/m/y');
$Backup_Name=$_POST['Backup_Name'];
$Tape_Code = $_POST['Tape_Code'];
$Operator_Approval = $_POST['Operator_Approval'];
$Operator_Remark = $_POST['Operator_Remark'];
$abc=mysqli_query($MySQLiconn,"insert into backup_details(Date, Backup_Name, Tape_Code,Operator_Approval,Operator_Remark)values('$Backup_Name','$Tape_Code','$Operator_Approval','$Operator_Remark')");
}
?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<?php $Date=date( 'd/m/y'); ?>
<form name="form2" action="" method="post">
<table>
<tr>
<td width="103">Date</td>
<td width="94">Backup_Name</td>
<td width="94">No Of Tapes</td>
<td width="53">Tape Code</td>
<td width="71">Operator Approval</td>
<td width="144">Operator Remark</td>
</tr>
<?php if ($que->num_rows > 0) { while ($row = mysqli_fetch_array($que)) { ?>
<tr>
<td>
<?php echo $Date; ?>
</td>
<td>
<?php echo $row[ 'Backup_Name']; ?>
</td>
<td>
<input type="text" name="No_Of_Backup">
</td>
<td>
<div class="field_wrapper">
<input type="text" name="Tape_Code" value="" />add
</div>
</td>
<td>
<input type="text" name="Operator_Approval">
</td>
<td>
<input type="text" name="Operator_Remark">
</td>
<td colspan="8">
<input type="submit" name="confirm" value="Confirm">
</center>
</td>
</tr>
<?php } } ?>
</table>
</form>
</body>
</html>
I'm doing this code in php. I need a help to add text fields dynamically in to the table's particular column. I have done the code using JavaScript also. But the problem is when I add field in one row, all rows are updating with extra fields. I need a help. How can I insert those data to MySQL?
The problem with your code is that you are using the class selector to select the elements. Class selector returns array like object of all the elements having that class.
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
you can find out which element was clicked if you change your code similar to below one.
add
and in the script
function addButton(ev) {
var clickedElement = console.log(ev.target);
}
Now you have the element which was clicked by user and you can find the parent td/tr and append html for textbox.
In $Tape_Code = $_POST['Tape_Code']; You will get array of text input you have to insert it in database in form that you want.
$Tape_Code = $_POST['Tape_Code']
foreach($Tape_Code as $code){
echo $code;
}

how can return array values if first element is null in php

I need to insert array values into database.But i can not insert array
values properly when first value of array is null.How can i fix my
problem
<form name=myform action="addcanteen.php" method=post>
<table><tr><td width="11%"> Date:</td><td width="89%"><input type="date" name="cdate" id="cdate"/></td></tr></table>
<table border="1" bgcolor="#F5F9C1">
<tr>
<!--<th>ID</th>-->
<th>Name</th>
<td><!--<input type="text" id="datepicker">-->
<input type="checkbox" id="selectall" name="chk[]"/></td>
<td align="center">coffee</td>
<td align="center">tea</td>
</tr>
<?php while($row=mysql_fetch_array($result))
{
?>
<tr>
<?php /*?><td><?php echo $row['emp_id'];?></td><?php */?>
<td><?php echo $row['emp_name'];?></td>
<td align="center"><input type="checkbox" class="name" name="chk1[]" value="<?php echo $row['emp_name'];?>"/></td>
<td><input type="text" name="coffee[]" id="coffee" value="" /></td>
<td><input type="text" name="tea[]" id="tea" value=""/></td>
</tr>
<?php } ?>
<tr>
<td>
</td>
<td>
</td>
<td align="center">
<input type="submit" class="button" name="submit" id="submit" value="submit"/>
</td>
</tr>
</table>
</form>
above is my form and this is my insertion code.I inserted entire value if it is not null.But if first one is null i can not insert into database
<?php
include(dbcon.php);
date_default_timezone_set('UTC');
$date=date("d");
$month=date("m");
$year=date("Y");
$fd=date("d-m-Y");
if(isset($_POST['submit']))
{
$cdate=$_POST['cdate'];
$checkbox1=$_POST['chk1'];
$tea=$_POST['tea'];
$coffee=$_POST['coffee'];
for ($i=0; $i<sizeof($checkbox1);$i++)
{
$query1="INSERT INTO canteen(name,coffee,tea,date)VALUES('".$checkbox1[$i]."','".$coffee[$i]."','".$tea[$i]."','$cdate')";
$sql1=mysql_query($query1);
}
}
header("location:canteen.php");
?>
This is my java script for the function select the check box
$(function () {
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.name').attr('checked', this.checked);
});
// if all checkbox are selected, then check the select all checkbox
// and viceversa
$(".name").click(function () {
if ($(".name").length == $(".name:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
maybe... try this:
for ($i=0; $i<sizeof($checkbox1);$i++)
{
if($checkbox1[$i] != null && $coffee[$i] != null && $tea[$i] != null) {
$query1="INSERT INTO canteen(name,coffee,tea,date)VALUES('".$checkbox1[$i]."','".$coffee[$i]."','".$tea[$i]."','$cdate')";
$sql1=mysql_query($query1);
}
}

img by changing it's src and is drawn by a dynamically provided source (mysql and php) with a Javascript

I have these scripts:
<?
/*//Disable error reporting
error_reporting(0);
*/
//Report runtime errors
//error_reporting(E_ERROR | E_WARNING | E_PARSE);
//Report all errors
error_reporting(E_ALL);
//end of error reporting
?>
<html>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('select').on('change', function(e){
var selected_value = $(this).val();
var option_data = $(this).children('option[value="'+selected_value+'"]');
// get data values
var visanumber = option_data.data('visanumber');
var idnumber = option_data.data('idnumber');
var statusapp = option_data.data('statusapp');
var subdate = option_data.data('subdate');
// the photo
var accntvisaphotopath = option_data.data('accntvisaphotopath');
if(accntvisaphotopath == 'data-passport=') {
$(this).closest('td').siblings().find('img.accntVisaPhotoPath').attr('src', 'accntvisaphotopath');
$(this).closest('td').siblings().find('img.passportPath').attr('src', 'passportpath');
} else {
$(this).closest('td').siblings().find('img.passportPath').attr('src', 'passportpath');
$(this).closest('td').siblings().find('img.accntVisaPhotoPath').attr('src', 'accntvisaphotopath');
}
// set the values
$(this).closest('td').siblings().find('span.visanumber').text(visanumber);
$(this).closest('td').siblings().find('span.idnumber').text(idnumber);
$(this).closest('td').siblings().find('span.statusapp').text(statusapp);
$(this).closest('td').siblings().find('span.subdate').text(subdate);
});
</script>
</head>
<body>
<?
$con=mysqli_connect("localhost","xxx","xxxx","xxxx");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL:" . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT * FROM visa ORDER BY idvisa");
?>
<div align="center">
<form name="contractInfo" method="post" enctype="multipart/form-data" accept-charset="UTF-8">
<table border="1px" width="700">
<tr>
<td align="center" colspan="7"><b>Email:</b><input name="email" type="text" id="email"></td>
</tr>
<tr>
<th> <div align="center"> Applicant Name </div></th>
<th> <div align="center">Visa Number</div></th>
<th> <div align="center">ID Number </div></th>
<th> <div align="center">Employment Status</div></th>
<th> <div align="center"> Visa </div></th>
<th> <div align="center"> Passport </div></th>
<th> <div align="center"><font color="red">Elapse</div></th>
</tr>
<tr>
<td>
<select>
<? echo "<option value=\"\">Select Person:</option>";?><br>
<? while ($row=mysqli_fetch_array($result)) {
echo "<option value=".$row['idvisa']." data-visanumber=".$row['visanumber']." data-idnumber=".$row['idnumber']." data-statusapp='{$row['statusapp']}' data-accntVisaPhotoPath=".$row['accntVisaPhotoPath']." data-passport=".$row['passportPath']." data-subdate='{$row['subdate']}'>".$row['fName']." ".$row['lName']."</option>";
}
?>
</select>
<?//Additional var
//Time
$today = date("Y/m/d G:i:s");
$date= $row["subdate"];
$days = strtotime($today) - strtotime($date);
//End Time
?>
</td>
<td><span class="visanumber"></span></td>
<td><span class="idnumber"></span></td>
<td><span class="statusapp"></span></td>
<td align="center"><img class="accntVisaPhotoPath" height="50" width="50"></img></td>
<td align="center"><img class="passportPath" height="50" width="50"></img></td>
<td><span class="subdate"></span></td>
</span>
</tr>
<tr>
<td>
<select>
<?
mysqli_data_seek( $result, 0 );
echo "<option value=\"\">Select Person:</option>";
while ($row=mysqli_fetch_array($result)) {
echo "<option value=".$row['idvisa']." data-visanumber=".$row['visanumber']." data-idnumber=".$row['idnumber']." data-statusapp='{$row['statusapp']}' data-accntVisaPhotoPath=".$row['accntVisaPhotoPath']." data-passport=".$row['passportPath']." data-subdate='{$row['subdate']}'>".$row['fName']." ".$row['lName']."</option>";
}
?>
</td>
<td><span class="visanumber"></span></td>
<td><span class="idnumber"></span></td>
<td><span class="statusapp"></span></td>
<td align="center"><img class="accntVisaPhotoPath" height="50" width="50"></img></td>
<td align="center"><img class="passportPath" height="50" width="50"></img></td>
<td><span class="subdate"></span></td>
</span>
</tr>
</table>
<br><br>
<input type="button" name="cancelvalue" value="CANCEL" onClick="self.close()">
<input name="reset" type="reset" value="Clear" height="14">
<input name="submit" type="submit" value="Send" height="14">
<br><br>
</form>
</body>
</html>
and may aim is to change it's src
<td align="center"><img class="accntVisaPhotoPath" height="50" width="50"></img></td>
<td align="center"><img class="passportPath" height="50" width="50"></img></td>
I have tried to search in here but it seems I am too dumb in revising what I have found. I know, it is simple but I am new in handling custom data attributes and then have the Javascript populate it all BUT the image has caught me unprepared.
And my L A B is here.
I suggest use classes in this case, don't use ID because it will have multiple rows.
<td><span class="visanumber"></span></td>
<td><span class="idnumber"></span></td>
<td><span class="statusapp"></span></td>
<td align="center"><img class="accntVisaPhotoPath" height="50" width="50"></td>
<td align="center"><img class="passport" height="50" width="50"></td>
<td><span class="subdate"></span></td>
Then, just target that option based on the value you selected. Then extract those data attributes values according to selection.
<script type="text/javascript">
$(document).ready(function(){
$('select').on('change', function(e){
var selected_value = $(this).val();
var option_data = $(this).children('option[value="'+selected_value+'"]');
// get data values
var visanumber = option_data.data('visanumber');
var idnumber = option_data.data('idnumber');
var statusapp = option_data.data('statusapp');
var subdate = option_data.data('subdate');
// the photo
var accntVisaPhotoPath = option_data.data('accntvisaphotopath');
$(this).closest('td').siblings().find('img.accntVisaPhotoPath').attr('src', accntVisaPhotoPath);
var passportPath = option_data.data('passportpath');
$(this).closest('td').siblings().find('img.passportPath').attr('src', passportPath);
// set the values
$(this).closest('td').siblings().find('span.visanumber').text(visanumber);
$(this).closest('td').siblings().find('span.idnumber').text(idnumber);
$(this).closest('td').siblings().find('span.statusapp').text(statusapp);
$(this).closest('td').siblings().find('span.subdate').text(subdate);
});
});
</script>
Of course the path of the images is up to you since no PHP codes are found in your question, this is just an example.
Here is a working demo:
http://codepad.viper-7.com/GhH6Yh
thanks
Your get Image Path should return a image to show up, try this:
function getImagePath(){
return "https://www.google.com/images/srpr/logo11w.png";
}
Now, you need to add parameter to getImagePath function and and the functions should return the appropriate image url.

Categories

Resources