I'm trying to make 3 form fields (a dropdown list dynamically populated by a .php script and 2 text fields) and also with a button add 3 more and 3 more and so on (as user clicks the button) I have tried several ways but nothing seems to work for me. (I'm noob in JS, AJAX, jQuery so I mostly tried scripts I've found on the internet).
Here's the code of these form fields:
<form id="form1" name="form1" method="post" action="results.php">
<div id="itemRows">
<select name="species">
<option value="">Select Species</option>';
<?php $sql = "SELECT common FROM species";
$speciesq = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($speciesq))
{
echo "<option value=\"" . $row['common'] ."\">" . $row['common'] ."</option>";
}
?>
</select>
Number: <input type="text" name="speciesnumber1" size="7" /> Weight: <input type="text" name="speciesweight1" /> <input onClick="addRow(this.form);" type="button" value="+" />
</div></form>
and after this form there's the code:
<script type="text/javascript">
var rowNum = 0;
var ddsel = '<select name="species'+rowNum+'>';
var ddopt = '<option value="">Select Species</option>';
var ddselc= '</select>';
function addRow(frm) {
rowNum ++;
$.post("getlist.php", function(data) {
for (var i=0; i<data.length; i++) {
ddopt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
}
}, "json");
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.add_qty.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.add_name.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
getlist.php is a simple script that populates the dropdown list and sends the data:
<?php
include("dbcon.php");
$sql = mysqli_query ($con, "SELECT common FROM species");
$result = array();
while ($row = mysqli_fetch_array($sql)){
$result[] = array(
'value' => $row['common'],
);
}
echo json_encode($result);
?>
So when I click the "+" button (to add the row) nothing happens.
SOLVED: for those who come here please read also the comments below the answer.
You just have some code in the wrong spot:
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.add_qty.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.add_name.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
needs to be moved into the post return function like this:
function addRow(frm) {
rowNum ++;
$.post("getlist.php", function(data) {
var frm = document.getElementById('form1');
for (var i=0; i<data.length; i++) {
ddopt += '<option value="'+data[i].value+'">'+data[i].value+'</option>';
}
var row = '<p id="rowNum'+rowNum+'">'+ddsel+ddopt+ddselc+'Number: <input type="text" name="speciesnumber'+rowNum+'" size="7" value="'+frm.add_qty.value+'"> Weight: <input type="text" name="speciesweight'+rowNum+'" value="'+frm.add_name.value+'"> <input type="button" value="-" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
}, "json");
}
Related
I have an associative array $row[Description, Name, ID_Item]. When a user select "Name" by event onchange into function I want to pass 2 variables $row[Description] and $row[ID_Item].
So, I guess it should be something like:
<form action="/delete.php" method="post">
<select name="NameSelect" id="ID_Select" onchange = "ShowItemInfo('.$row['ID_Item'].', '.$row['Description'].' ,)">
<?php
while ($row = $res->fetch_assoc())
{
echo '<option value = " '.$row['Description'].''.'¶'.''.$row['ID_Item'].' " > '.$row['Name'].' </option>';
}
mysqli_free_result($res);
mysqli_close($conn);
?>
</select>
It doesn't work, so can anybody help? Because due to inability to pass these variables I have to pass them via DOM with separator "¶" but it is obviously a crutch:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Delete your records</title>
</head>
<body>
<h2>
<?php
$conn = mysqli_connect("www.mywebsite.com", "username", "password", "Goods")
or die ('Cannot connect to db');
$query = "select ID_Item, Name,Description from Item";
$res = mysqli_query($conn, $query);
?>
<form action="/delete.php" method="post">
<select name="NameSelect" id="ID_Select" onchange = "ShowItemInfo()">
<?php
while ($row = $res->fetch_assoc())
{
echo '<option value = " '.$row['Description'].''.'¶'.''.$row['ID_Item'].' " > '.$row['Name'].' </option>';
}
mysqli_free_result($res);
mysqli_close($conn);
?>
</select>
<button type="submit"> Delete! </button>
<br> <br> <br> <br>
<textarea id="Desc" name="Desc" rows="4" cols="50" readonly>
Please, choose an item!
</textarea>
<br><br><br><br>
<label for="ID_Item">Identificator of an item:</label>
<input type="number" id="ID_Item" name="ID_Item" value="42" readonly >
</form>
</h2>
<script>
function ShowItemInfo() {
var str = document.getElementById("ID_Select").value;
var res = str.split("");
var Id = 0;
var Description = "";
var i = 1;
while (res[i] != "¶") {
Description = Description.concat(res[i]);
i++;
}
for (var j = i+1; j < res.length - 1; j++) {
Id = 10 * Id + parseInt(res[j],10);
}
document.getElementById("Desc").value = Description;
document.getElementById("ID_Item").value = Id;
}
</script>
</body>
</html>
Instead of adding values using separator you can use custom html attributes and set one value inside these attributes . So , your php code for options will look like below :
echo '<option desc=".$row['Description']." value = ".$row['ID_Item']." > '.$row['Name'].' </option>';
Demo Code :
function ShowItemInfo() {
//get selector
var selector = document.getElementById("ID_Select")
var Id = selector.value; //value
var Description = selector.options[selector.selectedIndex].getAttribute("desc"); //custom attribute desc
//set them
document.getElementById("Desc").value = Description;
document.getElementById("ID_Item").value = Id;
}
<select name="NameSelect" id="ID_Select" onchange="ShowItemInfo()">
<option desc="soemthing1" value="1"> sss</option>
<option desc="soemthing2" value="2"> sss2</option>
<option desc="soemthing3" value="3"> sss3</option>
</select>
<button type="submit"> Delete! </button>
<br> <br> <br> <br>
<textarea id="Desc" name="Desc" rows="4" cols="50" readonly>
Please, choose an item!
</textarea>
<br><br><br><br>
<label for="ID_Item">Identificator of an item:</label>
<input type="number" id="ID_Item" name="ID_Item" value="42" readonly>
Update 1 :
You can achieve same by passing value whenever onchange event is called .
Demo Code :
function ShowItemInfo(Id, Description) {
//set them
document.getElementById("Desc").value = Description;
document.getElementById("ID_Item").value = Id;
}
<!--pass values as parameter using `this`-->
<select name="NameSelect" id="ID_Select" onchange="ShowItemInfo(this.value,this.options[this.selectedIndex].getAttribute('desc'))">
<option desc="soemthing1" value="1"> sss</option>
<option desc="soemthing2" value="2"> sss2</option>
<option desc="soemthing3" value="3"> sss3</option>
</select>
<button type="submit"> Delete! </button>
<br> <br> <br> <br>
<textarea id="Desc" name="Desc" rows="4" cols="50" readonly>
Please, choose an item!
</textarea>
<br><br><br><br>
<label for="ID_Item">Identificator of an item:</label>
<input type="number" id="ID_Item" name="ID_Item" value="42" readonly>
function check_uncheck(truefalse) {
var boxes = document.forms[0].chkboxarray.length;
var form = document.getElementById('checkForm');
for (var i = 0; i < boxes; i++) {
if (truefalse) {
form.chkboxarray[i].checked = true;
} else {
form.chkboxarray[i].checked = false;
}
}
}
<form name="checkForm" id="checkForm" method="post" action="checkboxes1.php">
<input type="checkbox" name="chkboxarray" value="1" /><br />
<input type="checkbox" name="chkboxarray" value="2" /><br />
<input type="button" name="CheckAll" value="Check All Boxes" onclick="check_uncheck(true)" />
<input type="button" name="UncheckAll" value="Uncheck All Boxes" onclick="check_uncheck(false)" />
<input type="submit" value="Save">
</form>
The snippet shows how it works without connection to a database
I am trying to save the data that is sent from the checklist to a database but i'm stuck. I was thinking of using a foreach but I don't know what to put in it.
I though of putting it as:
foreach($_POST['id'] as $add){
insert into database...
}
How do I do this?
If I do this as Fred-ii and xjstratedgebx suggested where I just change name="chkboxarray" to name="chkboxarray[]" then the javascript code would stop working.
<?php
include '../conec.php';
mysql_select_db("test",$conec)or die('Database does not exist.') or die(mysql_error());
$sql = mysql_query("SELECT * FROM user WHERE state='Not Signed Up'");
?>
<form name="checkForm" id="checkForm" method="post" action="checkboxes1.php">
<?php
while($row = mysql_fetch_array($sql)){
$id = $row['id'];
$name = $row['name'];
$lName= $row['lName'];
$concate = $name.' '.$lName;
echo '<input type="checkbox" name="chkboxarray" value="'.$id.'" />'.$concate.'<br />';
}
?>
<!--<input type="checkbox" name="chkboxarray" value="1" /><br />
<input type="checkbox" name="chkboxarray" value="2" /><br />-->
<input type="button" name="CheckAll" value="Check All Boxes" onclick="check_uncheck(true)" />
<input type="button" name="UncheckAll" value="Uncheck All Boxes" onclick="check_uncheck(false)" />
<input type="submit" value="Save">
</form>
<script type="application/javascript">
function check_uncheck(truefalse){
var boxes = document.forms[0].chkboxarray.length;
var form = document.getElementById('checkForm');
for(var i=0;i < boxes;i++){
if (truefalse) {
form.chkboxarray[i].checked=true;
} else {
form.chkboxarray[i].checked=false;
}
}
}
</script>
If you change the name of your checkbox from "chkboxarray" to "chkboxarray[]", then any boxes that are checked when the form is submitted will pass their values as an array to the server under the key of "chkboxarray".
Basically, change this line:
echo '<input type="checkbox" name="chkboxarray" value="'.$id.'" />'.$concate.'<br />';
To:
echo '<input type="checkbox" name="chkboxarray[]" value="'.$id.'" />'.$concate.'<br />';
As a result, if you var_dump the $_POST super global, you should see something like:
array(1) {
[chkboxarray]=>
array(2) {
[0]=>
string(1) "3"
[1]=>
string(1) "4"
}
}
In the example above, the checkboxes for id's 3 and 4 were checked, so they were sent to the server.
Once you have that array, inserting it into your database depends heavily on what you're trying to accomplish and your database's schema.
Hope that helps.
Also, in fairness, this is exactly what #Fred meant in his comment.
Edit 1
To make the javascript work with the change of the input name, you'll need to update all the places in your javascript where you were referencing the name of the input to the new name (chkboxarray[]).
The resulting code should look like this:
<script type="application/javascript">
function check_uncheck(truefalse) {
var boxes = document.forms[0]["chkboxarray[]"].length;
var form = document.getElementById('checkForm');
for (var i = 0; i < boxes; i++) {
if (truefalse) {
form["chkboxarray[]"][i].checked = true;
} else {
form["chkboxarray[]"][i].checked = false;
}
}
}
</script>
I've created a fiddle to show this works for checking/unchecking all the boxes: https://jsfiddle.net/solvomedia/3Ln468u3/
Am hoping to ask another question here since the main one was answered on this thread:
How fill form data from Dropdown?
Though its abit of a continuation.
I am attempting to use javascript and an onChange() function to scroll through the files and then display them in the text input and text area fields on the form however I would appreciate any help in resolving my javascript. As it stands right now I can pull the file into the dropdown menu, but when I select one from the dropdown menu, nothing happens or populates on the form.
edited to update All errors seem to be resolved however nothing gets moved into the text boxes when selecting a file from the dropdown menu.
Javascript:
<script>
function CodeChange() {
var filesContentJS = "$filesContents"
var index = filesContentJS.selectedIndex;
var e = document.getElementById("CodeList");
var strUser = e.options[e.selectedIndex].value;
strUser = "0";
integer document.getElementById("CodeId").value = 0;
document.getElementById("CodeName").value = "";
document.getElementById("CodeValue").value = "";
}
</script>
updated javascript
And the form html and php itself for reference:
<input type="hidden" name="Action" value="EDIT" /><input type="hidden" name="Selection" id="Selection" value="-1"><div>Below is the list of your saved codes. To edit your codes, select it from the list.</div>
<select size="1" name="CodeList" id="CodeList" onchange="CodeChange();"><option value="0">(Add New Code)</option>
<?php
$directory = $directory = 'users/' . $_SESSION['username'];
$filesContents = Array();
$files = scandir( $directory ) ;
foreach( $files as $file )
{
if ( ! is_dir( $file ) )
{
$filesContents[$file] = file_get_contents($directory , $file);
echo "<option>" . $file . "</option>";
}
}
?>
</select>
<h3>Saved Codes</h3>
<form method="post" action="/evo/avsaveprocess.php">
<input type="hidden" name="Action" value="SAVE" />
<input type="hidden" name="CodeId" id="CodeId" value="0" />
<table width="100%" border="0">
<tr>
<td>Description:</td>
<td><input type="text" name="CodeDescription" size="40" maxlength="50" id="CodeName" value="" /></td>
</tr>
<tr>
<td valign="top">Code:</td>
<td>
<textarea rows="10" style="width:99%" name="Code" id="CodeValue"></textarea>
</td>
</tr>
</table>
<input type="submit" value="Save" />
</form>
Your PHP array is still an array. You have to convert it to JS.
So, after you did all the $filesContents[$file] = file_get_contents($directory , $file);, then you need JS:
<script>
var filesContentJS = <?=json_encode($filesContents) ?>;
function CodeChange() {
var e = document.getElementById("CodeList"); // getting dropdown element
if (e.selectedIndex<=0) { // nothing selected - clean form
document.getElementById("CodeId").value = 0;
document.getElementById("CodeName").value = "";
document.getElementById("CodeValue").value = "";
} else {
var eStr = e.options[e.selectedIndex].value; // getting current element value
// fill the form with data
document.getElementById("CodeId").value = 0;// not sure what CodeId is - but this is the place to fill it
document.getElementById("CodeName").value = eStr;
document.getElementById("CodeValue").value = filesContentJS[eStr];
}
</script>
Try with
var e = document.getElementById("CodeList");
var strUser = e.options[e.selectedIndex].value;
I want to pass values to a PHP script so i am using AJAX to pass those and that part works. But in the same function I want retrieve those values that I passed to the PHP script. The problem is I cannot retrieve any value from the PHP file. I have search high and low, but now come to you for answers. How can I store the variable passed on to the PHP script so that my ajax can retrieve it? My code is as follows:
This is my form :
<!-- file album.php -->
<html>
<head>
<?PHP
include ("conection/connect.php");
?>
<script type="text/javascript" src="jstbl/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
function cekjumlah(tableID)
{
var hitung=document.getElementById(tableID).rows.length;
var jumlah = hitung-1;
document.getElementById("media").value=jumlah;
}
</script>
</head>
<title></title>
<body>
<form name="form1" id="form1" method="post">
Jumlah Inputan :
<input type="text" id="media" name="media" size="5">
<input type="text" id="data_barang" name="data_barang" size="60" onKeyPress="onEnterPenjualan(event);">
<br><br>
<table id="tabelimei" border="1">
<tr id="Last">
</tr>
</table>
<br><br>
<div id="menu">
<p>
<input type="submit" name="simpan" value="Simpan" onClick="cekjumlah('tabelimei')">
<input onClick="deleteRow('DivTambah')" name="button" type="submit" value="Hapus" />
</p>
<p id="hasil">hasil</p>
</div>
</form>
</body>
</html>
And this is my jquery :
function onEnterPenjualan(e){// => Digunakan untuk membaca karakter enter
var key=e.keyCode || e.which;
if(key==13){// => Karakter enter dikenali sebagai angka 13
$(function(){
var data_barang = $("#data_barang").val();
$.ajax({
url: "ambildatabarang.php",
data: "data_barang="+data_barang,
cache: false,
success: function(data){
console.log(data);
alert(data);
}
});
var nama = alert (data.$nama);
var baris = document.getElementById("data_barang").value;
var i = 1;
var row = $(document.createElement('tr')).attr("id", 'DivTambah' + i);
row = '<tr>'+
'<td>1</td>'+
'<td><input name="cek[0]" id="cek" type="checkbox" size="10" /></td>'+
'<td><input name="qty_penjualan[0]" type="text" id="qty_penjualan" value="1" size="10" required/></td>'+
'<td><input type="text" name="imei_penjualan[0]" id="imei_penjualan" size="60" value="'+baris+'" required/></td>'+
'<td><input type="text" name="nama_penjualan[0]" id="nama_penjualan" size="30" value = "'+nama+'"required/></td>'+
'<td><input type="text" name="hargajual_penjualan[0]" id="hargajual_penjualan" value="300000" size="15" required/></td>'+
'<td><input type="text" name="diskon_penjualan[0]" id="diskon_penjualan" size="15" value="0"/></td>'+
'<td><input type="text" name="total_penjualan[0]" id="total_penjualan" size="15" value="300000" required/></td>'+
'<td><button type="button" class="del">Del</button></td>'+
'</tr>';
$(row).insertBefore("#Last");
var hapus = "";
document.getElementById('data_barang').value=hapus;
document.getElementById('data_barang').value.focus();
i++;
});
$(".del").live('click', function(){
$(this).parent().parent().remove();
});
}}
And this is my PHP file :
<?php
if (isset($_GET['data_barang'])){
// Instructions if $_POST['value'] exist
include ("conection/koneksidb.php");
$databarang = $_GET['data_barang'];
$datalengkapbarang = mysql_query("SELECT i.id_imeibarang, jb.nama_jenisbarang, b.type_barang, b.hargajual_barang FROM jenisbarang jb, barang b, imeibarang i WHERE i.id_imeibarang='$databarang' and i.idbarang_imeibarang=b.id_barang and b.idjenis_barang=jb.id_jenisbarang");
$angka = 1;
while($k = mysql_fetch_array($datalengkapbarang)){
echo $no[$angka] = $angka;
echo $imei[$angka]=$k['id_imeibarang'];
echo $nama[$angka]=$k['nama_jenisbarang'].$k['type_barang'];
echo $harga[$angka]=$k['hargajual_barang'];
$angka = $angka+1;
}
}
?>
to send the some data to php and get the result of the php file to javascript synchronously, this is what you need
function sendData (data1,data2)
{
if (window.XMLHttpRequest)
AJAX=new XMLHttpRequest();
else
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
if (AJAX)
{
AJAX.open("POST", "url.php", false);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.send("data1=" + data1 + "&data2=" + data2);
return AJAX.responseText;
}
else
return null;
}
now, on your php file, you just get your data like this
$data1 = $_POST['data1'];
$data2 = $_POST['data2'];
once you work with the data in your php file, and then you echo the result, it is returned by the javascript function, so you just need to use it like this in your javascript file
var data_from_php = sendData(data1,data2);
I'm facing this trouble..
I have this JavaScript code:
echo "<script type=\"text/javascript\">
var counter = 1;
function addInput(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = \"Entry \" + (counter + 1) + \" <input type='text' name='myInputs[]'>\";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
</script> ";
and this PHP code:
$produkty="SELECT * FROM goods ORDER BY name";
if (isset($_POST['order'])) {
$name = $_POST['myInputs'];
foreach( $name as $key => $n ) {
print $n." thank you\n <br />";
}
}
echo "
<fieldset><form method='post'>
<div id='dynamicInput'>
<select name='idp[]'>";
$vys = mysqli_query($db, $goods);
while ($arr = mysqli_fetch_assoc($vys)) {
echo "<option value='".$arr['id_good']."'>".$arr['name']."</option>";
}
echo "
</select> <br />
Entry 1 <input type='text' name='myInputs[]''><br />
</div>
<input type='button' value='Add another text input' onClick=\"addInput('dynamicInput');\"><br />
<input type='submit' name='order'>
</form></fieldset>
";
and I use it to "generate" new (html) input everytime submit is clicked.
But I need to generate not only those (html) inputs, but also that (html) select, which processes the values from the database and show it as options in that (html) select.
I searched a lot to find out the way to "insert" the part from <select .. to </select> to the newdiv.innerHTML variable, but it wasn't succesful. I find some hints that I should "parse" the PHP code in (html) select and then create variable $no1 = mysqli_query($db, $goods); $no2 = while ($arr = mysqli_fetch_assoc($no1)... ... and in the end just say JavaScript newdiv.innerHTML = <?php echo $no5; ?>; .. but there were many problems with the syntax and with the principles that discouraged me.
Can you help me please? ;)
Here is a rough sketch of what you can do for this, if I am understanding you correctly.
<?php
$options = "";
$vys = mysqli_query($db, $goods);
while ($arr = mysqli_fetch_assoc($vys)) {
$options .= "<option value='".$arr['id_good']."'>".$arr['name']."</option>";
}
echo <<< _html
<form method="post">
<div id="dynamicInput">
<div>
<select name=idp[]>
$options
</select> <br />
Entry 1 <input type="text" name=myInputs[]><br />
</div>
</div>
<input type="button" value="Add another text input" onClick="addInput('dynamicInput');"><br />
<input type="submit" name="order">
</form>
_html;
?>
<script type="text/javascript">
var counter = 1;
function addInput(divName){
var newdiv = document.createElement('div');
newdiv.innerHTML = "<select name=idp[]><?php echo $options; ?></select> Entry " + (counter + 1) + " <input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
</script>
Hope this helps...