PHP Undefined $_POST input created via Javascript createElement and appendChild - javascript

I am creating dynamic input rows to POST it into MySQL database
the first row is mandatory, so I created the FORM and Inputs via HTML for the first row
Then created a button and addEventListener function to append any additional row dynamically
Error
Actually, all nodes and children are working normally from the DOM side without any problem
When I submit the form, only the first static row is posted but any appended rows give Undefined array key
myJsFile.js
document.getElementById('add_row').addEventListener('click',function(e){
var my_tbody = document.querySelector('.my_tbodyClass');
var my_tr = document.createElement('tr');
my_tbody.appendChild(my_tr);
var my_div = document.createElement('div');
var my_td = document.createElement('td');
var my_input = document.createElement('INPUT');
my_input.setAttribute('type','number');
my_input.setAttribute('name','myRows[]');
my_tr.appendChild(my_td);
my_div.appendChild(my_input);
my_td.appendChild(my_div);
});
myphpFile.php
function execute_dynamicRow()
{
global $dbConnection;
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['submitedDynamicRows'])) {
$myRows = $_POST['myRows'];
$myRowsSerialized = serialize($myRows);
$stmt = mysqli_prepare($dbConnection, "INSERT INTO all_dynamic_rows(dynamic_rows) VALUES(?)");
$stmt_bind_param = mysqli_stmt_bind_param($stmt, 's', $myRowsSerialized);
$stmt_execute = mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
if (!$stmt) {
die("Query Error " . mysqli_error($dbConnection));
}
}
}
myform.php
<?php myform(); ?>
<form method="post">
<table class="table table-flush">
<thead>
<tr>
<th class="text-uppercase text-secondary">Add You Number</th>
<th class="text-uppercase text-secondary">Add Row</th>
</tr>
</thead>
<tbody class="my_tbodyClass">
<tr>
<td>
<div>
<input type="number" name="myRows[]">
</div>
</td>
<td>
<button class="btn btn-icon btn-3" id="add_row" type="button">
<span class="btn-inner--text">Add New Row</span>
</button>
</td>
</tr>
</tbody>
</table>
<div class="input-group input-group-outline my-3">
<input type="submit" name="submitedDynamicRows" class="btn btn-info" value="Add Tax Slab">
</div>
</form>

Related

Not able to insert the data in input field of form

I have a form, there is a button (+sign)on the form which appends a row to insert the value .In my form i am able to enter the value on the first row both fields( stationerytype and stationeryqty). But once I append a new row by clicking plus button I am not able to insert any value on staionerytype field of second row while I'm able to insert the value in the stationeryqty field of second row.
My code is:
<table class="table table-bordered" id="tb" >
<tr class="tr-header">
<th class= "col-md-1" align="centre">Sl.No.</th>
<th class= "col-md-6" align="centre">STATIONARY TYPE</th>
<th class= "col-md-4" align="centre">STATIONARY QUANTITY</th>
<th class= "col-md-1"><span class="glyphicon glyphicon-plus"></span></th>
</tr>
<tr>
<?php
for($i=1;$i<=1;$i++)
{
?>
<td><input type="text" style="text-decoration: none" name="slno" value= "<?php echo $i; ?>" ></td>
<td><input type="text" style="text-decoration: none" name="stationerytype" ></td>
<td><input type="number" name="stationeryqtyrecd" id="stationeryqtyrecd" min="0"></td>
<td><a href='javascript:void(0);' class='remove'><span class='glyphicon glyphicon-remove'></span></a></td>
</tr>
<?php }?>
</table>
<button type="submit" name="add" class="btn btn-info" align="middle" >ADD </button>
<script>
var max = 4;
var count = 1;
$(function(){
$('#addMore').on('click', function() {
if(count <= max ){
var data = $("#tb tr:eq(1)").clone(true).appendTo("#tb");
data.find("input").val('');
debugger;
data.find("input")[0].value=++count;
}else{
alert("Sorry!! Can't add more than five samples at a time !!");
}
});
$(document).on('click', '.remove', function() {
var trIndex = $(this).closest("tr").index();
if(trIndex>1) {
$(this).closest("tr").remove();
} else {
alert("Sorry!! Can't remove first row!");
var trIndex = $(this).closest("tr").index();
if(trIndex>1) {
$(this).closest("tr").remove();
count--;
// get all the rows in table except header.
$('#tb tr:not(.tr-header)').each(function(){
$(this).find('td:first-child input').val(this.rowIndex);
})
}
});
});
</script>
</div>

Storing count of table rows in a JS variable

I have some old code I am trying to poke through. This table is loaded via a Controller action returning a model, based off of a button click somewhere else in the page.
How can I find the number of rows in the table in a JS variable? I am terrible with JS. I have tried a few things and nothing has worked. Below is my code and also what I have tried to do to store the num of rows.
Table:
<hr />
<div class="row" id="ReceiptsMainDiv">
<div class="col-md-12" style="overflow-y:scroll">
<table class="table table-striped table-hover table-bordered" id="terminalReceipts">
<thead>
<tr>
<th>Terminal ID</th>
<th>Local Transaction Time</th>
<th>Amount</th>
<th>Receipt</th>
<td class="hidden"></td>
</tr>
</thead>
<tbody>
#foreach (var item in Model.TransactionsTests)
{
<tr id="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">
<td>#item.TerminalID</td>
<td>#item.TransactionTime</td>
<td>#item.Amount</td>
#*<td>#Html.ActionLink("View Receipt", "ViewReceipt", new { id = item.Id }, new { #class = "btn btn-primary btn-sm" }) <br /></td>*#
<td class="transactionID hidden">#item.Id</td>
<td>
#if (item.ReceiptData == null)
{
<button class="btn btn-sm btn-primary viewReceipt" disabled>View Receipt</button>
}
else
{
<button class="btn btn-sm btn-primary viewReceipt" data-rowindex="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">View Receipt</button>
}
</td>
</tr>
}
</tbody>
</table>
</div>
Here is what I have tried to do in JS:
var rowId = "#" + $(this).data("rowindex");
var row = $(rowId);
console.log(rowId);
console.log(row);
Results from the console.log don't appear to be accurate. Anything helps. Thanks
Probably you want the number of rows of your table.
// javascript
var rowsInTable = document.getElementById("terminalReceipts").getElementsByTagName("tr").length;
//jquery
var rowsInTable2 = $("#customers").children('tbody').children('tr').length;
//if you need to do something with the rows:
var rows = $("#customers").children('tbody').children('tr');
rows.each(function( index ) {
console.log( index + ": " + $( this ).text() );
});
you can also do that using jquery like this
var totalRowCount = $("#terminalReceipts tr").length; //this will give +1 row
var rowCount = $("#terminalReceipts td").closest("tr").length; //this will give actual row

Hiding and un-hiding table div based off of data being returned

I have a table that I want to be hidden there is no data to be displayed.
I have a controller action that returns data to display for the table. If data is returned, I want the table to be show, otherwise I want it hidden. I have tried several approaches to this and it seems like my fix is working (for a few seconds) but then once the controller returns the model, the table becomes hidden again. I am doing something wrong. How can I fix this? Below is my code:
HTML:
#using (Html.BeginForm(null, null, FormMethod.Post, new { id = "submitForm"}))
{
<div class="row">
<div>
#Html.DropDownList("CasinoID", Model.TerminalReceiptPostData.CasinoIdDDL, "Select Casino", new { id = "cIdSearch", #class = "custom-class-for-dropdown card" })
</div>
<div>
<input id="datepicker" class="datepicker-base card" name="Date" placeholder="MM/DD/YYY" type="text"/>
</div>
<div>
<button type="submit" class="btn btn-sm btn-primary" id="search"> Search Transactions</button>
</div>
</div>
}
<hr />
<div class="row" id="ReceiptsMainDiv">
<div class="col-md-12" style="overflow-y:scroll">
<table class="table table-striped table-hover table-bordered" id="terminalReceipts">
<thead>
<tr>
<th>Terminal ID</th>
<th>Local Transaction Time</th>
<th>Amount</th>
<th>Receipt</th>
<td class="hidden"></td>
</tr>
</thead>
<tbody>
#foreach (var item in Model.TransactionsTests)
{
<tr id="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">
<td>#item.TerminalID</td>
<td>#item.TransactionTime</td>
<td>#item.Amount</td>
#*<td>#Html.ActionLink("View Receipt", "ViewReceipt", new { id = item.Id }, new { #class = "btn btn-primary btn-sm" }) <br /></td>*#
<td class="transactionID hidden">#item.Id</td>
<td>
#if (item.ReceiptData == null)
{
<button class="btn btn-sm btn-primary viewReceipt" disabled>View Receipt</button>
}
else
{
<button class="btn btn-sm btn-primary viewReceipt" data-rowindex="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))">View Receipt</button>
}
</td>
</tr>
}
</tbody>
</table>
</div>
</div>
Controller action:
[HttpPost]
public ActionResult Index(string CasinoID, DateTime Date)
{
//var id = Int32.Parse(Request.Form["CasinoID"].ToString());
var Cid = Request.Form["CasinoID"];
Cid = GetNumbers(Cid);
var id = Int32.Parse(Cid);
var model = TRBL.GetTransactionTestsData(id, Date);
model.TerminalReceiptPostData = TRBL.GetCasinosDDL();
return View(model);
}
and finally my JS function:
window.onload = function () {
$("#ReceiptsMainDiv").toggle();
var rowCount = $("#rowindex").length;
console.log(rowCount);
if (rowCount > 0) {
$("#ReceiptsMainDiv").toggle();
}
};
As you can see, the Form at the top contains the button, and the block below is the table that needs to be toggled.
Let me know if there is anything else you guys would need.
When you have results to show, <tr id="#String.Concat("rowIndex", Model.TransactionsTests.IndexOf(item))"> will not produce ids of "rowIndex" (unlike what you might be expecting). Instead, you will have "rowIndex0", "rowIndex1", etc. Therefore, after rowCount will be zero, and your will not toggle.

save link assign value as well as go to other page

I have a table where user can add data in it and I also have input field and save link. In my save link, if I click it.. I assign value to input field before it will go to other page. But when it go to the other page and I echo the value of inputfield, I got empty as in null value.
here's my code:
for table:
<table class="table " id="memberTB">
<thead>
<tr>
<th >First Name</th>
<th >Middle Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr id="first">
<td><span class="edit"></span></td>
<td><span class="edit"></span></td>
<td><span class="edit"></span></td>
</tr>
</tbody>
<button type="button" class="btn btn-link" id="addrow">
<span class="fa fa-plus"> Add new row</span>
</button>
</table>
<input type="text" name="list" id="list"/>
<br>
<a class="btn" id="savebtn">Save</button>
Reset
and for js:
$('#savebtn').click(function() {
var cells = 3; //number of collumns
var arraylist = []
var x=0;
$('tbody tr',$('#memberTB')).each(function(){
var cell_text = '';
for(var i = 0 ; i < cells ; i++){
if(i==2){
cell_text =cell_text+$(this).find('td').eq(i).text()+":";
}else{
cell_text =cell_text+$(this).find('td').eq(i).text()+",";
}
}
arraylist.push(cell_text);
});
document.getElementById("list").value =arraylist;
document.getElementById("savebtn").href="<?php echo site_url('test/save');?>";
}
I got nothing when I echo it in the test.php in the save(), like this:
echo $this->input->post('list');
You are simply redirecting the page. So you will not get any value from post. If you want to get the value by post method you need to submit the value with a form.
<form id='save_form' method="post" action="<?php echo site_url('test/save');?>">
//add your html codes
//<table ..... and others
<a class="btn" href="#" id="savebtn">Save</button> //add # to href for save button
</form>
Now your js
$('#savebtn').click(function() {
//js codes that you wrote
//just replace the following line
//document.getElementById("savebtn").href="<?php echo site_url('test/save');?>";
$('#save_form').submit();
}

Counting rows on a particular table

I have a page that the user can dynamically add rows or tables to. I need to count the rows on a given table using jQuery to see if I just need to insert a row or a row and the header. Right now the count is just counting all rows on all tables. I am using jQuery 1.7.2 and the jquery templeter.
<div id="ClonePoint">
<button id="exitSection" class="closesection"><span>Close</span></button> <br /> <br />
<button class="btnEncode" id="buttonEncode">Encode</button>
<input id="encryptedTokenClone" />
<button class="btnDecode" id="buttonDecode">Decode</button>
<table class="tokenTable" cellpadding="3px">
<tbody class="tokenBody" >
</tbody>
</table>
<button id="addRow" class="addingRow">Add Row</button>
</div>
And the jQuery that is adding the rows
$('#BackgroundArea').on('click', '.addingRow', function () {
var selectedDiv = $(this).parent();
var selectedTable = $(selectedDiv).children('.tokenTable');
var rowCount = 0;
rowCount = $('.tokenTable .tokenBody').children('tr').length;
if (rowCount > 0) {
$("#tokenAddRowTemplate")
.tmpl()
.appendTo(selectedTable);
} else {
$("#TableHeader")
.tmpl()
.appendTo(selectedTable);
$("#tokenAddRowTemplate")
.tmpl()
.appendTo(selectedTable);
}
});
The html for the insert is
<script id="TableHeader" type="text/html">
<tr id="TableHead">
<th width="55px">Delete Row</th>
<th align="right"> Key </th>
<th align="left"> Value </th>
</tr>
</script>
<script id="tokenAddRowTemplate" type="text/html">
<tr id="tokenRow">
<td class="deleteRow" id="tokenCell">
<button class="deleteRow">
<span>delete row</span>
</button>
</td>
<td class="keyValue" id="tokenCell">
<div class="edit" contenteditable="true"></div>
</td>
<td class="valueValue" id="tokenCell">
<div class="edit" contenteditable="true"></div>
</td>
</tr>
</script>
This should give tr count in your table.
$("#yourTableId tr").length
Is this what your are looking for ?
If each table is followed by its own "Add Row" button:
var $table = $(this).prev(),
rowCount = $table.find('.tokenBody').children('tr').length;
if (rowCount > 0) {
...
This assumes the "Add Row" button immediately follows the table.
To make the code less brittle, you could consider using a container element, like this:
<div class="tokenTableContainer">
<table class="tokenTable">
...
<table>
<button class="addingRow">...</button>
</div>
Then you can do this:
$('.addingRow').click(function() {
var $table = $(this).closest('.tokenTableContainer').find('.tokenTable');
...
});

Categories

Resources