Adding rows in the table with javascript - javascript

I have one form which has master detail data. i have created one table for details and creating rows on button click using JavaScript, but as soon as i am clicking add row button it is adding row and immediately my page gets reloaded so the added row disappears. i have another buttons to perform other PHP tasks so i can not remove form tag. please help me to get this done.
following is the HTML and JavaScript code.
<div class="row pt-3">
<div class="table-responsive">
<table id="vattable" class="table table-sm table-striped">
<thead class="thead-light">
<tr>
<th><?php echo GetBilingualLabels($_SESSION['$language'],"VATSETUP","VSDID"); ?></th>
<th><?php echo GetBilingualLabels($_SESSION['$language'],"VATSETUP","VSDSCATEGORY"); ?></th>
<th><?php echo GetBilingualLabels($_SESSION['$language'],"VATSETUP","VSDRATE"); ?></th>
<th><?php echo GetBilingualLabels($_SESSION['$language'],"VATSETUP","VSDAUTOFLAG"); ?></th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="text-control input-sm" readonly name="vsdid[]" id="vsdid" value=1 style="text-align:right" maxlength="13" /></td>
<td><input type="text" class="text-control" name="vsdscategory[]" id="vsdscategory1" style="text-align:right" maxlength="13" /></td>
<td><input type="text" class="text-control" name="vsdrate[]" id="vsdrate1" style="text-align:right" maxlength="13" /></td>
<td><input type="text" name="vsdautoflag[]" id="vsdautoflag1" style="text-align:right" maxlength="13" autofocus /></td>
</tr>
</tbody>
</table>
</div>
</div>
<script>
$(document).ready(function() {
$('[data-toggle="tooltip"]').tooltip();
var count=1;
$(document).on('click','#addrow', function(){
//alert('a');
count=count+1;
$('#vsdid').val(count);
//alert(count);
var html_code='';
html_code +='<tr id="row_id_'+count+'">';
html_code += '<td><input type="text" class="text-control input-sm" name="vsdid[]" id="vsdid'+count+'" style="text-align:right"/></td>';
html_code +='<td><input type="text" class="text-control" name="vsdscategory[]" id="vsdscategory'+count+'" /></td>';
html_code +='<td><input type="text" class="text-control" name="vsdrate[]" id="vsdrate'+count+'" style="text-align:right" maxlength="13" /></td>';
html_code +='<td><input type="text" name="vsdautoflag[]" id="vsdautoflag'+count+'" style="text-align:right" /></td>';
html_code +='<td><button type="submit" name="removerow" id="removerow" class="btn btn-danger fa fa-minus"></button></td></tr>';
$('#vattable').append(html_code);
//alert(html_code);
});
});
</script>

It's possible that your #addrow button is the submit button and the form is being submitted. Add a return false just after //alert(html_code)

You haven't added a button to add the rows, so you're likely observing a side effect.
If I understand correctly, you want to have a button that on click will execute the function you've created. Therefore, you can add a button with id addrow below the table div like this:
<button id="addrow">
Add Row
</button>
And then you can attach your function via jQuery as you've started (I have slightly amended your script) - see JsFiddle - https://jsfiddle.net/9Ljc237k/9/

in your add row button click you should return false at the end,
or set type attribute of your button tag to button instead of submit
also is better to append row to tbody tag not table

If you have the problem only with reload you should put event.preventDefault()
$(document).on('click','#addrow', function(event){
event.preventDefault();
//alert('a');
count=count+1;
$('#vsdid').val(count);
//alert(count);
var html_code='';
html_code +='<tr id="row_id_'+count+'">';
html_code += '<td><input type="text" class="text-control input-sm" name="vsdid[]" id="vsdid'+count+'" style="text-align:right"/></td>';
html_code +='<td><input type="text" class="text-control" name="vsdscategory[]" id="vsdscategory'+count+'" /></td>';
html_code +='<td><input type="text" class="text-control" name="vsdrate[]" id="vsdrate'+count+'" style="text-align:right" maxlength="13" /></td>';
html_code +='<td><input type="text" name="vsdautoflag[]" id="vsdautoflag'+count+'" style="text-align:right" /></td>';
html_code +='<td><button type="submit" name="removerow" id="removerow" class="btn btn-danger fa fa-minus"></button></td></tr>';
$('#vattable').append(html_code);
//alert(html_code);
});

Related

how to fetch the data from database in dynamically created table using codeiginter

<table class="table table-bordered table-striped table-xxs" id="tb3" name="tb3">
<thead>
<tr>
<th></th>
<th>Product Code</th>
<th>Product Name</th>
<th>Qty</th>
<th>Rate</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<tr >
<td><a href='javascript:void(0);' class='remove3'><span class='glyphicon glyphicon-remove'></span></a></td>
<td>
<input style="width:80px" type="text" id="Product_Code" class="form-control input-xs Product_Code " onkeyup="fetch()" value="<?php echo $r->Product_Code; ?>" name="Product_Code[]" required></td>
<td ><input style="width:300px" type="text" id="Product_Name" class="form-control input-xs" value="<?php echo $r->Prdtname; ?>" name = "Prdtname[]" value=""> </td>
<td><input style="width:80px" type="text" id="Qty" class="form-control input-xs" value="<?php echo $r->Qty; ?>" name="Qty[]" required></td>
<td><input style="width:100px" type="text" id="Rate" class="form-control input-xs" value="<?php echo $r->rate; ?>" name="rate[]" required></td>
<td><input style="width:150px" type="text" id="Value" class="form-control input-xs" value="<?php echo $r->amount; ?>" name="amount[]" ></td>
<th><span class="glyphicon glyphicon-plus"></span></th>
</tr>
</tbody>
</table>
this table code....
<script>
$(document).ready(function (){
$('#addMore3').on('click', function() {
var data = $("#tb3 tr:eq(1)").clone(true).appendTo("#tb3");
data.find("input").val('');
});
$(document).on('click', '.remove3', function() {
var trIndex = $(this).closest("tr").index();
if(trIndex>0) {
$(this).closest("tr").remove();
} else {
alert("Sorry!! Can't remove first row!");
}
});
});
</script>
this is javascript code for creating table by clicking "+" event.
My prblm is how to fetch data from database display in this automatic table..
You should be able to do this using ajax call.
As you are using codeigniter -
View : Write your ajax and table generation code.
Controller: get the ajax request and pass it to modal.
Modal: get the data from database.
you should return array of object to view and then just parse the data and generate table.
If you dont want to write the table code and ajax then you can use datatable plugin.

Passing multiple parameters with serialize jQuery in PHP

I have a problem with a serialized form. I need to pass multiple rows for creating an invoice, but it passes just the first row.
This is a form:
<form action="" id="generate_invoice" method="POST">
<td><input type="number" class="form-control n_invoice" name="n_invoice[]"></td>
<td><input type="date" class="form-control data" name="data[]"></td>
<td><input type="text" class="form-control description" name="description[]"></td>
<td><input type="number" class="form-control price" name="price[]" step=any></td>
<td><input type="number" class="form-control vat" name="vat[]">
</form>
This is a function which adds new rows:
function addrow_invoice() {
var i = $('#invoiceTable tr').length;
var tr = '<tr>'+
'<td><input type="checkbox" class="case"/></td>'+
'<td></td>'+
'<td></td>'+
'<td><input type="text" class="form-control description" name="description[]"></td>'+
'<td><input type="number" class="form-control price" name="price[]"></td>'+
'<td><input type="number" class="form-control vat" name="vat[]"></td>'+
'</tr>';
$('table#invoiceTable').append(tr);
i++;
};
And this is a test:
for($i = 0; $i<count($_POST['description']); $i++)
{
echo "{$_POST['description'][$i]}";
echo "<br>";
}
The issue is because your HTML is invalid. The form needs to wrap the table element, not be inside it. Because the HTML is invalid, the location of the form is moved so that it's not wrapping your input elements, hence nothing gets serialised.
Your HTML needs to be changed to this:
<form action="" id="generate_invoice" method="POST">
<table id="invoiceTable">
<tr>
<td><input type="number" class="form-control n_invoice" name="n_invoice[]"></td>
<td><input type="date" class="form-control data" name="data[]"></td>
<td><input type="text" class="form-control description" name="description[]"></td>
<td><input type="number" class="form-control price" name="price[]" step=any></td>
<td><input type="number" class="form-control vat" name="vat[]">
</tr>
<!-- additional rows appended here... -->
</table>
</form>

Dynamic Rows for Table in a Form

I'm trying to create a form that can dynamically add more rows to a table as needed. In the example that I will post you will see a table for chaperones. Since, we do not know off hand how many chaperones each school will bring it needs to be dynamic. I'm trying to use Javascript to create an onclick button that will add a new row to the table and storing the names as an array so that it can be sent POST and analyzed using PHP and then stored into the database. I found a solution online, however when I try to implement it on my site nothing is working once I click the button. Maybe I just need another set of eyes to look it over and see if I need anything.
<table id="chp" class="table table-striped">
<tr>
<th class="text-center">First Name</th>
<th class="text-center">Last Name</th>
<th class="text-center">Phone</th>
<th class="text-center">Email</th>
<th class="text-center"> + </th>
</tr>
<tr>
<td><input id="chpFirst" name="chpFirst" type="text" placeholder="John" class="form-control input-md" required=""></td>
<td><input id="chpLast" name="chpLast" type="text" placeholder="Doe" class="form-control input-md" required=""></td>
<td><input id="chpPhone" name="chpPhone" type="text" placeholder="5555555555" class="form-control input-md" required=""></td>
<td><input id="chpEmail" name="chpEmail" type="text" placeholder="john.doe#email.com" class="form-control input-md" required=""></td>
<td><input type="button" id="more_fields" onclick="add_chp();" value="Add" class="btn btn-info" /></td>
</tr>
</table>
<script>
function add_chp() {
document.getElementByID("chp").insertRow(-1).innerHTML = '<tr>' +
'<td><input id="chpFirst" name="chpFirst[]" type="text" placeholder="John" class="form-control input-md" required=""></td>' +
'<td><input id="chpLast" name="chpLast[]" type="text" placeholder="Doe" class="form-control input-md" required=""></td>' +
'<td><input id="chpPhone" name="chpPhone[]" type="text" placeholder="5555555555" class="form-control input-md" required=""></td>' +
'<td><input id="chpEmail" name="chpEmail[]" type="text" placeholder="john.doe#email.com" class="form-control input-md" required=""></td>' +
'<td><input type="button" id="more_fields" onclick="add_fields();" value="Add More" class="btn btn-info" /></td>' +
'</tr>';
}
</script>
https://jsfiddle.net/owk9ct13/
JavaScript is case sensitive:document.getElementByID wont work. Replace that with document.getElementById and it should fix your issue.
Also as a tip, be sure to check the any error or warning messages in the browser console...it makes debugging the front end way easier.

jquery calculate on dynamically added rows

I`ve dynamiclally added rows, and i want to auto calculate values on it.
Here are part of my code:
<table id="itemsTable" class="general-table">
<thead>
<tr>
<th></th>
<th>Код на продукт</th>
<th>Описание</th>
<th>Брой</th>
<th>Цена</th>
</tr>
</thead>
<tbody>
<tr class="item-row">
<td></td>
<td><input name="itemCode[]" value="" class="tInput" id="itemCode" tabindex="1" /> </td>
<td><input name="itemDesc[]" value="" class="tInput" id="itemDesc" readonly="readonly" /></td>
<td><input name="itemQty[]" value="" class="tInput" id="itemQty" tabindex="2"/></td>
<td><input name="itemPrice[]" value="" class="tInput" id="itemPrice" readonly="readonly" /> </td>
</tr>
</tbody>
</table>
<span> <img src="images/icon-plus.png" alt="Add" title="Add Row" /> Добави ред</span>
<div style="float: right; width: 100px;">
<div id="container">Общо: <span style="clear:both;" id="added"></span><br></div>
</div>
And jquery
$('input').keyup(function(){ // run anytime the value changes
var firstValue = parseFloat($('#itemQty').val()); // get value of field
var secondValue = parseFloat($('#itemPrice').val()); //
$('#added').html(firstValue * secondValue); // add them and output it
});
The problem is that that script calculate only the first row.
You have repeated IDs in your webpage. And whenever you will use repeated IDs it will always treated for the first Element. So, you have to make dynamic ids for this purpose:
Making HTML with PHP:
<table id="itemsTable" class="general-table">
<thead>
<tr>
<th></th>
<th>Код на продукт</th>
<th>Описание</th>
<th>Брой</th>
<th>Цена</th>
</tr>
</thead>
<tbody>
<?php
foreach( $yourArray as $key=>$item){}
?>
<tr class="item-row">
<td></td>
<td><input name="itemCode[]" value="" class="tInput" id="itemCode_<?php echo $key;?>" tabindex="1" /> </td>
<td><input name="itemDesc[]" value="" class="tInput" id="itemDesc_<?php echo $key;?>" readonly="readonly" /></td>
<td><input name="itemQty[]" value="" class="tInput" id="itemQty_<?php echo $key;?>" tabindex="2"/></td>
<td><input name="itemPrice[]" value="" class="tInput" id="itemPrice_<?php echo $key;?>" readonly="readonly" /> </td>
</tr>
<?php
}
?>
</tbody>
</table>
<span> <img src="images/icon-plus.png" alt="Add" title="Add Row" /> Добави ред</span>
<div style="float: right; width: 100px;">
<div id="container">Общо: <span style="clear:both;" id="added"></span><br></div>
</div>
Javascirpt/JQuery:
$(document).ready(function(){
$('input').keyup(function(){ // run anytime the value changes
// getting parent TR of current Input
var parent_tr = $(this).closest('tr');
//gettting parent TR's child input named as 'itemQty[]'
var firstValue = parseFloat($("input[name='itemQty[]']", parent_tr).val()); // get value of field
//gettting parent TR's child input named as 'itemPrice[]'
var secondValue = parseFloat($("input[name='itemPrice[]']", parent_tr).val()); //
$('#added').html(firstValue * secondValue); // add them and output it
});
});
Demo will Static HTML 2 rows: http://jsfiddle.net/Lvjff4ga/
$('input','#itemsTable').change(function(){
var tot = 0;
$('tbody tr','#itemsTable').each(function(){
tot += $('[name=itemQty\[\]]', this).val() * $('[name=itemPrice\[\]]', this).val();
});//each
$('#added').html(tot);
});

jquery .find() is not returning value

I have gone through this before, but I don't know what I am doing wrong. I also take a look the documentation plus the existing question on Stack Overflow but I could not find any answer. This drives me crazy. I know I missed something but I could not trace it. This is what I have in index.php
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/file.js"></script>
<?php
echo '<table border="1" width="50%">';
foreach($datas as $data){
echo '<form method="post" action="" class="vForm">';
echo '<tr><td><input type="text" name="qty" value="1" size="3" /></td></tr>';
echo '<tr><td><input type="submit" name="add" value="add" class="button" /></td></tr>';
echo '</form>';
}
echo '</table>';
So in my file.js
$(function() {
var CA = (function() {
function add(form) {
console.log('Form: ' + form.find('[name="qty"]').val() );
return false;
}
$('.vForm').submit(function(e) {
add($(this));
e.preventDefault();
});
}());
});
For some reason I could not able to get the "qty" value in the text field in file.js. The code below also failed. I just got "undefined" in the console log.
console.log('Form: ' + form.find('input[name="qty"]').val() );
Any help is greatly appreciated. Thank you.
Well, after reading the comments section, and after the actual code is provided.. I believe the reason is quite simple:
The form element is not a valid child of the table element. Your code basically, renders the following.
<table>
<form method="post" action="" class="vForm">
<tr>
<td><input type="text" name="qty" value="1" size="3" /></td>
</tr>
<tr>
<td><input type="submit" name="add" value="add" class="button" /></td>
</tr>
</form>
</table>
As stated in the W3C Specification, the only valid children of the table element are 'caption', 'col' or 'colgroup', 'thead', 'tfoot', or 'tbody'.
I don't know how jQuery's .find() method specifically works, when it gets to how jQuery is programmed, but fixing this invalid html results in your desired effect:
<form method="post" action="" class="vForm">
<table>
<tr>
<td><input type="text" name="qty" value="1" size="3" /></td>
</tr>
<tr>
<td><input type="submit" name="add" value="add" class="button" /></td>
</tr>
</table>
</form>
Demo, illustrating the above(check your console).
MY dear friend it is working fine.
<?php
$datas=array("Volvo","BMW","Toyota");
foreach($datas as $data){
echo '<form method="post" action="" class="vForm">';
echo '<input type="text" name="qty" value="'.$data.'" size="3" />';
echo '<input type="submit" name="add" value="add" class="button" />';
echo '</form>';
}
?>
Please check the screen shot and in input area i took the $data's value.

Categories

Resources