Java script problem While inserting data in form - javascript

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><select id="stationerytype" name="stationerytype[]" autocomplete="off">
<option >Stationery Name</option>
<?php $sql = "SELECT stationerytype from tblstationerytype order by stationerytype ASC ";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{ ?>
<option value="<?php echo htmlentities($result->stationerytype);?>"><?php echo htmlentities($result->stationerytype);?></option>
<?php }} ?>
</select></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>
Java script code is below
<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>

Related

Few field of INPUT form not allowing to enter Data

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>

Generate Sl No on the Form on button click

I have a form with three input fields named sl no ,stationerytype and stationeryqty There is a symbol + and - to append or delete these three field on click. I am trying the sl no field to generate Sl no automatically when i click the plus symbol and if I click - it will automatically adjust the sl no. but My sl no field remains blank .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('');
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!");
}
});
});
</script>
</div>
Thanks for any suggestion :-)
in your addMore function after erasing data from the newly created row just add one more line to set the serial number in first td.
$('#addMore').on('click', function() {
if(count <= max ){
var data = $("#tb tr:eq(1)").clone(true).appendTo("#tb");
debugger;
data.find("input").val('');
//set the count value in first td
data.find("input")[0].value = ++count;
}else{
alert("Sorry!! Can't add more than five samples at a time !!");
}
});
working javascript fiddle example

JavaScript Remove <tr> Table Row Dynamically

I'm trying to remove row from my dynamic table. I've success to .append new row from JavaScript.
JavaScript
$(document).ready(function() {
// table #pos add-row
$(".add-row").keypress(function(e) {
if (e.which == 13) {
var barcode = $("#barcode").val();
$.ajax({
type: "post",
url: "production/ajax/load.php",
dataType: "json",
data: {
barcode: $("#barcode").val()
},
success: function(data) {
$("#pos tbody").append(data['content']);
}
});
}
});
// Find and remove selected table rows
$(".delete-row").click(function(){
alert('Success');
$("#pos tbody tr").remove();
});
})
load.php
<?php
if (isset($_POST['barcode'])) {
require '../controller/connection/connection-management.php';
$barcode = $_POST['barcode'];
$status = false;
$sql = "SELECT code, title, wri_name, pub_name, year, main_category.main_category, category.category, call_number, pusat_penerbit, mrican, paingan, selling_price, discount FROM product, writer, publisher, main_category, category WHERE product.writer = writer.writer AND product.publisher = publisher.publisher AND product.main_category = main_category.main_category AND product.category = category.category AND code = '{$barcode}' ORDER BY title";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) == 1) {
while($row = mysqli_fetch_assoc($result)) {
$barcode = $row['code'];
$title = $row['title'];
$sellingPrice = number_format($row['selling_price'], 0, ',', '.');
$quantity = 1;
$discount = $row['discount'];
$total = number_format((($row['selling_price'] - ($row['selling_price'] * ($discount / 100))) * $quantity), 0, ',', '.');
$append = "<tr class='pointer'>
<td align='right'><a href='javascript:;' class='delete-row'><i class='fa fa-trash'></i></a></td>
<td><small>{$barcode}</small></td>
<td><div style='text-align: justify'><strong>{$title}</strong></div></td>
<td align='right'>{$sellingPrice}</td>
<td align='center'><input id='quantity' type='text' class='form-control' style='text-align:center' value='1'></td>
<td align='center'><input type='text' class='form-control' style='text-align:center' value='{$discount}'></div></td>
<td align='right'>{$total}</td></td>
</tr>";
}
$status = true;
}
$data = array(
"status" => $status,
"content" => $append
);
echo json_encode($data);
}
?>
pos.php it's html table
<div class="x_title">
<div class="input-group">
<span class="input-group-btn">
<button type="button" class="delete-row btn btn-primary"><i class="fa fa-pencil-square-o"></i></button>
</span>
<input name="barcode" id="barcode" type="text" class="add-row form-control" placeholder="Enter item name or scan barcode">
<div class="input-group-btn">
<button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown" aria-expanded="false">Receive</button>
<ul class="dropdown-menu dropdown-menu-right" role="menu">
<li>Receive</li>
<li>Return</li>
<li>Purchase Order</li>
<li>Transfer</li>
<li>Store Account Payment</li>
</ul>
</div>
</div>
</div>
<div class="x_content">
<div class="table-responsive">
<table name="pos" id="pos" class="table table-striped jambo_table bulk_action">
<thead>
<tr class="headings">
<th style="text-align:center" class="column-title col-sm-7" colspan="3">Item Name </th>
<th style="text-align:right" class="column-title col-sm-1">Cost </th>
<th style="text-align:center" class="column-title col-sm-2">Qty. </th>
<th style="text-align:center" class="column-title col-sm-1">Disc % </th>
<th class="column-title col-sm-1" style="text-align:right">Total </th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
So when I add new row in the table, everything works fine like this picture:
But when I click trash icon with class='delete-row', that's is not working. So I think, when I append data to table tbody it's not read class or id from the new row.
Please someone help. I can't find any similar questions like mine. I just want to know, how to remove table row when I click trash icon from JavaScript.
You have two issues here (which is why I have not voted to close as a duplicate). Firstly you need to use a delegated event handler on the .delete-row element as it is appended to the DOM after load. Your current code does nothing as you attempt to attach the event handler before the element exists.
Secondly, you need to use DOM traversal to remove only the parent tr of the clicked button. At the moment your code would remove all rows. Try this:
$('#pos').on('click', '.delete-row', function() {
$(this).closest('tr').remove();
});
Did you tried delegate?
$(document).delegate('.delete-row', 'click', function(){
//your remove code here
});
You can also use on (for jquery versions 1.7.1+)
$(document).on('click', '.delete-row', function(){
//your remove code here
});

HTML form doesn't capture all the checkboxes from Bootstrap responsive table

I have a table which displays results from my DB. In the last column I have checkboxes and by clicking submit button I am sending an array of account_id's to another php file. Everything works fine but the problem is that I am using a Bootstrap responsive table which can show 10-100 results on each page and the form only captures results on the current page. If I check boxes on different pages and switch between them, they still remain checked, though.
Here is my HTML:
<form action="compare.php" method="post">
<table class="table table-hover" id="dataTables-example">
<thead>
<tr>
<th style="text-align:center;">Account name</th>
<th style="text-align:center;">Address</th>
<th style="text-align:center;">Phone number</th>
<th style="text-align:center;">Website</th>
<th style="text-align:center;">Compare</th>
</tr>
</thead>
<tbody>
<?php
$result= mysql_query("select * from accounts order by account_name ASC" ) or die (mysql_error());
while ($row= mysql_fetch_array ($result) ){
?>
<tr>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['account_name'];?></td>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['address']; ?></td>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['phone_number']; ?></td>
<td class='clickable-row' data-href="select.php?id=<?php echo $row ['account_id'];?>"> <?php echo $row ['website']; ?></td>
<td> <input type="checkbox" name="checkboxvar[]" value="<?php echo $row ['account_id'];?>" /></td>
</tr>
<?php } ?>
</tbody>
</table>
<input class="btn btn-success" type="submit" value="Compare" id="submit">
</form>
I tried to use jQuery to see if it can capture the checkboxes from the whole table, but results is the same as trying an HTML form.
This script is supposed to capture them and make an alert:
<button id="bt1">Get</button>
<script>
$('#bt1').on('click', function () {
//Get checked checkboxes
var checkedCheckboxes = $("#dataTables-example :checkbox:checked"),
arr = [];
//For each checkbox
for (var i = 0; i < checkedCheckboxes.length; i++) {
//Get checkbox
var checkbox = $(checkedCheckboxes[i]);
//Get checkbox value
var checkboxValue = checkbox.val();
//Get siblings
var siblings = checkbox.parent().siblings();
//Get values of siblings
var value1 = $(siblings[0]).text();
var value2 = $(siblings[1]).text();
arr.push(checkboxValue + '-' + value1 + '/' + value2);
alert(checkboxValue + '-' + value1 + '/' + value2);
}
});
</script>
Is there a way to do it?
You can use Datatables object:
$('input', oTable.fnGetNodes()).each(function () {
if($(this).is('checked')){
console.log($(this).val());
}
});
Solved!
Include this script:
<script type="text/javascript" src="//cdn.datatables.net/plug-ins/f2c75b7247b/api/fnGetHiddenNodes.js"></script>
And this paste this function:
<script>
$(document).ready(function() {
oTable = $('#yourTableID').dataTable();
$('form').submit(function(){
$(oTable.fnGetHiddenNodes()).find('input:checked').appendTo(this);
});
});
</script>
All checkboxes are captured by clicking submit button.

I'm trying to pull data from database into selectboxes

I'm trying to pull data from database into selectboxes, but when the data is pulled it goes into one 'td' and not into separate td's. I'm trying to achieve result as shown below
but I keep getting this result
here is my code
<?php
$data_array = array();
$result2 = mysql_query("SELECT * FROM `firefightersonscene`
JOIN `firefighterinfo` ON `firefightersonscene`.`FireFighterInfo_fighterID` = `firefighterinfo`.`fighterID`
JOIN `stationlocation` ON `firefighterinfo`.`StationLocation_locationID`=`stationlocation`.`locationID`
WHERE `IncidenceOfFire_incidentID`='$getIncID' ORDER BY `firstName`");
if(mysql_num_rows($result2) > 0)
{
while($rows2 = mysql_fetch_object($result2))
{
$data_array[] = $rows2;
}
}
?>
<form action="core_viewfireoccurrence.php?incidentID=<?php echo $rows->incidentID; ?>" method="post" class="view_occurrence_form">
<table id="myTable">
<thead>
<tr>
</tr>
</thead>
<tbody>
<tr>
<td class="count">1</td>
<td>
<?php
foreach($data_array as $rows2):
$fighterID = $rows2->FireFighterInfo_fighterID;
$results = mysql_query("SELECT `fighterID`, `firstName`, `middleName`, `lastName`, `stationlocation`.`exactlocation`
FROM `firefighterinfo`
JOIN `stationlocation` ON `firefighterinfo`.`StationLocation_locationID`=`stationlocation`.`locationID` ORDER BY `firstName`");
echo '<select name="fireman[]" required><option value=""></option>';
while($row = mysql_fetch_array($results))
{
if($row['fighterID'] == $fighterID)
echo '<option selected>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
else
echo '<option>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
}// end while
echo '</select><br>';
endforeach;
?>
</td>
<td>
<input type="button" value="X" class="removeVar"/>
</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>
<input type="button" id="addVar" value="Add Item"/>
</tr>
</tfoot>
</table>
</form>
JS CODE
<script type="text/javascript">
$('form').on('click', '.removeVar', function(){
$(this).closest('tr').remove();
$('.count').each(function(i){
$(this).text(i + 1);
});
});
//add a new node
$('#addVar').on('click', function(){
var varCount = $('#myTable tr').length - 1;
$node = ['<tr>',
'<td class="count">'+varCount+'</td>',
'<td><select name="fireman[]" class="ctlGroup" required>',
'<option value=""></option>',
'<?php require("php/fireman_list.php"); ?>',
'</select></td>',
'<td><input type="button" value="X" class="removeVar"/>',
'</td></tr>'].join('\n');
$('#myTable > tbody:last').append($node);
});
</script>
You need to put your whole table row in the loop. You will also need to add a variable to count the row number for you.
<?php
$row =1;
foreach($data_array as $rows2):
?>
<tr>
<td class="count"><?php echo $row; ?></td>
<td>
<?php
$fighterID = $rows2->FireFighterInfo_fighterID;
$results = mysql_query("SELECT `fighterID`, `firstName`, `middleName`, `lastName`, `stationlocation`.`exactlocation`
FROM `firefighterinfo`
JOIN `stationlocation` ON `firefighterinfo`.`StationLocation_locationID`=`stationlocation`.`locationID` ORDER BY `firstName`");
echo '<select name="fireman[]" required><option value=""></option>';
while($row = mysql_fetch_array($results))
{
if($row['fighterID'] == $fighterID)
echo '<option selected>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
else
echo '<option>'. $row['firstName']." ".$row['middleName']." ".$row['lastName'].", ".$row['exactlocation'].'</option>';
}// end while
echo '</select><br>';
?>
</td>
<td>
<input type="button" value="X" class="removeVar"/>
</td>
</tr>
<?php
$row++;
endforeach;
?>

Categories