I'm having a problem. I'm creating a dynamic table with jquery (the user insert a value and then it creates the table). Now in the Table I have a Select tab with pre-defined values that are coming from a table in my database (mysql).
this is my code:
$(document).ready(function() {
$("#submit").click(function(e) {
$("#Table").empty();
e.preventDefault();
if($("#NumOfLevels").val() >0)
{
var size = $("#NumOfLevels").val();
var str='';
str+='<table align="center" width="694" border="0" cellspacing="3" cellpadding="0">';
str+='<tr><th style="width:auto" scope="col">level </th><th width="107">score</th><th width="58">game file</th><th width="80">catalog</th><th width="93">start date</th><th width="85">end date/th></tr>';
for(var i = 0; i< size ; i++)
{
str+='<tr><td id="stage'+i+'" style="width:auto">level '+(i+1)+'</td><td><span id="sprytextfield4"><input type="text" name="Score" id="Score"/>';
str+='<span class="textfieldRequiredMsg">A value is required.</span></span></td>';
str+='<td><input type="file" name="gameFile" id="gameFile" /></td>';
str+='<td><select multiple="multiple" name="CatlogLink" id="CatlogLink">';
**Here Is Where I Need To Enter My PHP Function**
str+='</select></td>';
str+='<td><input type="text" class="date" id="datepicker" ></td>';
str+='<td><input type="text" class="date" id="datepicker2" "></td>';
//str.find('input').datepicker();
}
//str+='</tr></table>';
$("#Table").append(str);
var btn = '';
btn+='<tr><td width="192" colspan="2" align="center"><input type="submit" name="Submit" id="submit" value="submit"/></td>';
btn+='<td width="309" colspan="4" align="center"><input type="reset" name="reset" id="Clear" value="clear" /></td></tr></tr></table>';
$("#Table tr:last").after(btn);
}
$(".date").click(function() {
$( ".date" ).datepicker();
$( ".date" ).datepicker();
});
});
});
and my question is how to get the php code that generates the option list to integarte with my javascript code.
My Php Function only retrieve some values (Names) I don't send to the function any data.
Regards,
Yotam.
Related
I've been using JavaScript to create new row on the table so that each input data will save in database. please refer example below.
Script for adding row on the table
<script type="text/javascript">
$(document).ready(function(){
var html='<tr><td><input type="text" size="2" class="form-control" name="qt[]" id="qt"
oninput="calculate();" required></td>
<input type="text" size="5" class="form-control" name="uc[]" id="cf" oninput="calculate();"
placeholder="₱0.00" required></td>
<td><center><input type="text" size="5" class="form-control" name="ta[]" id="result"
required></center></td><input type="button" class="form-control" name="remove" id="remove"
value="-"></td></tr>';
var x = 1;
$("#addd").click(function(){
$("#tb_field").append(html);
});
$("#tb_field").on('click','#remove',function(){
$(this).closest('tr').remove();
x--;
});
});
</script>
Script for multiplying two input types in the first row of the table
<script>
function calculate() {
var myBox1 = document.getElementById("qt").value;
var myBox2 = document.getElementById("cf").value;
var result = document.getElementById("result");
var myResult = myBox1 * myBox2;
var format2 = myResult.toLocaleString("USD");
document.getElementById("result").value = format2;
}
</script>
I made a working JSFiddle example. The code is:
<table id="myTable">
</table>
<input type="button" name="addRow" id="addRow" value="+">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js?Version=43"></script>
<script>
function newRowHtml(rowNumber)
{
return '<tr id="row'+rowNumber+'"><td><input type="text" size="2" name="qt[]" class="qt" oninput="calculate('+rowNumber+');" value="0" required></td><td><input type="text" size="5" name="uc[]" class="cf" oninput="calculate('+rowNumber+');" value="0" required></td><td><center><input type="text" size="5" name="ta[]" class="ta" required></center></td><td><input type="button" name="remove" id="removeRow" value="-"></td></tr>';
}
var rowNumber = 1;
$("#addRow").click(function() {
$("#myTable").append(newRowHtml(rowNumber));
calculate(rowNumber);
rowNumber++;
});
$("#myTable").on('click', '#removeRow', function() {
$(this).closest('tr').remove();
});
function calculate(rowNumber)
{
let row = $("#row"+rowNumber);
let qt = parseInt(row.find(".qt").val());
let cf = parseInt(row.find(".cf").val());
row.find(".ta").val(qt * cf);
}
</script>
I have numbered the rows, which is easier than number cells, and make fully use of JQuery. I hope this makes some sense, and that you can adapt it to your needs.
You can, of course, use parseFloat() instead of parseInt(), but having values like ₱0.00 in your input could complicate things.
I have a scenario in my project module which allows user to enter as many values as he wants in a form. I have given an array name to the field but when i try to get these values in my controller then it only returns the first value of the array. I have used java-script to append new input fields dynamically.
I can't figure out what mistake i am making.
Here is My code.
My view
<h1> <small>Order Details</small></h1>
<table class="table " id="dynamic_field">
<tr>
<td>
<input type="text" name="product_name[]" id="name" class="form-control name_list" placeholder="Product Name">
</td>
<td>
<button type="button" name="submit" id="add" class="btn btn- success">Add More</button>
</td>
</tr>
</table>
JavaScript Code
<script type="text/javascript">
var i = 1;
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="product_name[]" id="last_class" class="form-control name_list" placeholder="Product Name"></td><td><button type="button" name="remove" class="btn btn-danger btn_remove" name="remove" id="'+i+'"> X</button></td></tr>')
});
$(document).on('click','.btn_remove',function() {
var button_id = $(this).attr("id");
$("#row"+button_id+"").remove();
});
</script>
When i try to print out the input field array using print_r it only returns the first value of the array even though we might have added more than 1 input fields.
Change your script and check
<script type="text/javascript">
var j = 1;
var i = 1;
$('#add').click(function()
{
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" name="product_name['+ j +']" id="last_class" class="form-control name_list" placeholder="Product Name"></td><td><button type="button" name="remove" class="btn btn-danger btn_remove" name="remove" id="'+i+'"> X</button></td></tr>');
j++ ;
});
$(document).on('click','.btn_remove',function()
{
var button_id = $(this).attr("id");
$("#row"+button_id+"").remove();
});
</script>
Try this in your controller
$names=$this->input->post('product_name') ;
foreach($names as $pname) {
echo $pname;
}
I am adding rows using java script functions by taking input and showing data into input text fields.
I am using this datepicker https://github.com/T00rk/bootstrap-material-datetimepicker.
When I input time the only first value of time is copied into input fields while rest two value are copied but time value is not copied.
<div style="width:90%;margin:auto;">
<h1>Simple example of dynamically adding rows with jQuery</h1>
<form method="post">
<div id="itemRows">
Item quantity: <input type="text" name="add_qty" size="4" /> Item name: <input type="text" name="add_name" />Time:<input type="text" id="time" name="time" />
(This row will not be saved unless you click on "Add row" first)
<input onclick="addRow(this.form);" type="button" value="Add row" />
</div>
<p><input type="submit" name="ok" value="Save Changes"></p>
</form>
<script type="text/javascript">
var rowNum = 0;
function addRow(frm) {
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'">Time<input type="text" id="time" name="time[]" size="4" value="'+frm.time.value+'" > Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"><input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
frm.time.value = '';
}
function removeRow(rnum) {
jQuery('#rowNum'+rnum).remove();
}
</script>
When you generate dynamic textbox with id and with date picker so you need to call one function for init datepicker on that text like below
$('input').bootstrapMaterialDatePicker();
function addRow(frm)
{
rowNum ++;
var row = '<p id="rowNum'+rowNum+'">Item quantity: <input type="text" name="qty[]" size="4" value="'+frm.add_qty.value+'">Time<input type="text" id="time'+rowNum+'" name="time[]" size="4" value="'+frm.time.value+'" > Item name: <input type="text" name="name[]" value="'+frm.add_name.value+'"><input type="button" value="Remove" onclick="removeRow('+rowNum+');"></p>';
jQuery('#itemRows').append(row);
frm.add_qty.value = '';
frm.add_name.value = '';
frm.time.value = '';
$('#time'+rowNum).bootstrapMaterialDatePicker();
}
In above function i add one id to time textbox and call bootstrap datepicker to init date on that textbox.
See working demo here
http://plnkr.co/edit/P0ZQsAjDJAXyJGs9kvT3?p=preview
I've been stuck on this for days. I really appreciate your help.
I'm working on a php form that generates dynamically added rows when
the user click the button ADD.
To save the values into the database, users must click the SUBMIT
button.
The problem that i'm facing is that the database doesn't save the
values from the dynamic rows.
AUTOCOMPLETE & DYNAMIC ROWS
<script>
//autocomplete
$(function() {
function log( message ) {
$( "<div>" ).text( message ).prependTo( "#log" );
$( "#log" ).scrollTop( 0 );
}
$( "#ItemName" ).autocomplete({
source: "user/requisition_search.php",
minLength: 1,
select: function( event, ui )
{
$('#ItmId').val(ui.item.id);
$('#StkId').val(ui.item.stkId);
$('#ItmNameDis').val(ui.item.value);
$('#ItmUOM').val(ui.item.uom);
$('#ItmQty').val(ui.item.qty);
}
});
});
//dynamic rows
$(document).ready(function(){
$("#add").on("click",function(){
var rowcount = $("#rowcount").val();
var row =
'<tr id="'+rowcount+'"><td>'+$("#ItmId").val()+'</td><td><input readonly="readonly" name="StkId[]" value="'+$("#StkId").val()+'"/></td><td>'+$("#ItemName").val()+'</td><td>'+$("#ItmUOM").val()+'</td><td>'+$("#ItmQty").val()+'</td><td><input readonly="readonly" name="ReqQty[]" value="'+$("#ReqQty").val()+'"/></td></tr>';
rowcount = parseInt(rowcount)+1;
$("#rowcount").val(rowcount);
$("#dataTab").append(row);
$("#dataTab").show();
$("#submit").show();
});
});
</script>
HTML
<form name="jqtest" action="submit.php" method="post">
<label for="ItemName">Search : </label>
<input id="ItemName" size="50"/>
<label for="ItmId">Item Id </label>
<input name="ItmId" id="ItmId" readonly="readonly"/>
<label for="StkId">Stock Id </label></td>
<input name="StkId" id="StkId" readonly="readonly"/>
<label for="ItmNameDis">Item Name </label>
<input name="ItmNameDis" id="ItmNameDis" size="50" readonly="readonly"/></td>
<label for="ItmUOM">Unit Of Measurement </label>
<input name="ItmUOM" id="ItmUOM" readonly="readonly"/>
<td><label for="ItmQty">Quantity Available </label>
<input name="ItmQty" id="ItmQty" readonly="readonly"/>
<label for="ReqQty">Quantity </label>
<input name="ReqQty" id="ReqQty" onkeypress="return numbersOnly(event)" onkeyup="ItmQty_Availability()" disabled="disabled"/>
<p>
<input type="reset" name="reset" id="reset" value="RESET"/>
<input type="button" name="add" id="add" value="ADD"/>
</p>
<input type="hidden" name="rowcount" id="rowcount" value="1"/>
<table id="dataTab" width="90%" style="display:none;" border="1" cellpadding="0" cellspacing="0">
<tr>
<th>Item ID</th>
<th>Stock ID</th>
<th>Item name</th>
<th>UOM</th>
<th>Quantity Available</th>
<th>Quantity Requested</th>
</tr>
</table>
<p> </p>
<p><input style="display:none;" type="submit" name="submit" id="submit" value="SUBMIT"/></p>
</form>
submit.php
<?php
$num = $_POST['rowcount'];
for($i=0;$i<$num;$i++)
{
$strStkId = "";
if(!empty($_POST)){
if(isset($_POST["StkId[]"])){
$strStkId = $_POST["StkId[]"];
}else{
echo "<font color=red>Enter the Stock Id</br></font>";
}
}
$strReqQty = "";
if(!empty($_POST)){
if(isset($_POST["ReqQty[]"])){
$strReqQty = $_POST["ReqQty[]"];
}else{
echo "<font color=red>Enter the Quantity</font>";
}
}
$tsql =
"INSERT INTO REQUISITION
(RequestQuantity, StockId)
VALUES
('$strReqQty','$strStkId')
";
$result = sqlsrv_query($conn, $tsql, array(), array( "Scrollable" => SQLSRV_CURSOR_KEYSET ));
if (!$result) {
die ('<script>
window.alert("Please enter the requisition details !")
window.location.href = "requisition.php"; </script>');
}
else
echo '<script>alert("Your Requisition is In Process"); </script>';
sqlsrv_close($conn);
}
?>
UPDATED
I've learnt that name="StkId" and name="StkId[]" clashes in the dynamic rows and the inputs.
So i've change into something like this :
var row = '<tr id="'+rowcount+'"><td>'+$("#ItmId").val()+'</td><td><input readonly="readonly" name="StkId2" value="'+$("#StkId").val()+'"/></td><td>'+$("#ItemName").val()+'</td><td>'+$("#ItmUOM").val()+'</td><td>'+$("#ItmQty").val()+'</td><td><input readonly="readonly" name="ReqQty2" value="'+$("#ReqQty").val()+'"/></td></tr>';
Now the data are inserted into the database but IF the user enters more than one item, only one data is inserted into the database. What did i do wrong? I guess its at the submit.php part but i can't figure out why.
You won't get dynamically generated row values in $_POST on submitting the form because those are not at all form inputs but just displaying as row in a table. But you can achieve your functionality with the help of jQuery AJAX. On clicking the submit button, calls your submit.php using AJAX. The sample solution for how to retrieve values of those dynamically rows is given below. You can adapt this method for your requirement.
Main Page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Dynamic Rows</title>
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
$("#add").on("click",function(){
var rowcount = $("#rowcount").val();
var row = '<tr class="dynamic" id="'+rowcount+'"><td>'+$("#itemid").val()+'</td><td>'+$("#itemname").val()+'</td><td>'+$("#uom").val()+'</td><td>'+$("#quantity").val()+'</td></tr>';
rowcount = parseInt(rowcount)+1;
$("#rowcount").val(rowcount);
$("#dataTab").append(row);
$("#dataTab").show();
$("#submit").show();
});
$("#submit").on("click",function(){
alert("submit");
var jsonObj = [];
i=0;
$("#dataTab tr.dynamic").each(function(){
var td = $(this).find('td');
itemId = td.eq(0).text();
itemName = td.eq(1).text();
uom = td.eq(2).text();
quantity = td.eq(3).text();
jsonObj.push({
itemId: itemId,
itemName: itemName,
uom: uom,
quantity: quantity,
});
});
var dataString = JSON.stringify(jsonObj);
$.ajax({
url: "submit.php",
type: "POST",
data: {json:dataString},
success: function(response){
alert(response);
}
});
});
});
</script>
</head>
<body>
<form name="jqtest" action="#">
Item ID : <input type="text" name="itemid" id="itemid"/><br/><br/>
Item name : <input type="text" name="itemname" id="itemname"/><br/><br/>
UOM : <input type="text" name="uom" id="uom"/><br/><br/>
Quantity : <input type="text" name="quantity" id="quantity"/><br/><br/>
<p> <input type="reset" name="reset" id="reset" value="RESET"/> <input type="button" name="add" id="add" value="ADD"/> </p>
<input type="hidden" name="rowcount" id="rowcount" value="1"/>
</form>
<table id="dataTab" style="display:none;" border="1">
<tr>
<th>Item ID</th>
<th>Item name</th>
<th>UOM</th>
<th>Quantity</th>
</tr>
</table>
<p> <input style="display:none;" type="button" name="submit" id="submit" value="submit"/> </p>
</body>
</html>
submit.php
<?php
$arr = json_decode($_POST['json']);
for($i=0; $i<count($arr); $i++)
{
echo "Row ".$i."\n";
echo "itemId > ".$arr[$i]->itemId.", itemName > ".$arr[$i]->itemName.", uom > ".$arr[$i]->uom.", quantity > ".$arr[$i]->quantity."\n";
}
?>
I have some code I am using that works well cloning the contents of a div as many times as needed.
The original code would rename the name/id of each form field. so the first clone the name would be "name1" second clone "name2" etc...
The problem is when I put the form fields within a div or a table for design purposes.
The code doesn't rename the form fields anymore as it seems to refer to the top elment which is the table or div (depending which I used)
Here is a cut down version of the code that contains everything needed for this example (can be copied into an editor and will work as is. You will see the field id's are not being renamed):
www.jsbin.com/oyavez/1/edit
<script type="text/javascript">
var formCounter = 0;
function init() {
document.getElementById('moreFields').onclick = moreFields;
moreFields();
}
function moreFields() {
formCounter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + formCounter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
window.onload = moreFields;
</script>
<title>Add Orders IO TOC</title>
</head>
<body>
<!-- Template -->
<div id="readroot" style="display: none">
<table>
<tr><td colspan="2"><h3>Order <script>document.write(formCounter);</script></h2></td></tr>
<tr><td>Order ID: </td><td><input type="text" id="OrderID name="OrderID[]" ></input></td>
<td>Order Name: </td><td><input type="text" id="OrderName" name="OrderName[]" ></input></td>
</table>
<br /><br /><input type="button" value="Remove Above Order" style="width:200px;" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br /><br />
<!-- ROW -->
</div>
<!-- END Template -->
<!-- Start of form -->
<form method="get" action="form.php">
<table>
<tr><td align="center" colspan="2"><h2>Contract</h2></td></tr>
<!-- Static part of the form not to be cloned -->
<tr><td>Contract: </td><td><input type="text" id="Contract" name="Contract" ></input></td>
<td>Signed Date: </td><td><input type="text" id="datepicker0" name="SignedDate" ></input></td>
<tr><td align="center" colspan="2"><h2>Orders</h2></td></tr>
</table>
<!-- ROW -->
<!-- Cloned parts of the form appear here -->
<span id="writeroot"></span>
<table>
<tr><td align="center" > <input type="button" style="width:200px;" value="Add another order below" onclick="moreFields()" /></td>
<td align="center" ><input type="submit" value="Submit IO and all Orders" style="width:200px;" ></td></tr>
</table>
</form>
Anyone know how to get to the child of the table it would seem?
Thanks!