Adding new row to the table using javascript / jquery - javascript

I want to add row to the table on clicking Add button and delete row using Delete button using javascript/jquery. I have tried writing the following code:
<script src="/js/jquery-2.0.3.js"></script>
<script>
/* Javascript for phone numbers*/
$(document).ready(function()
{
var counter = 2;
var count= 4;
$("#add_phone").click(function()
{
alert("whoah it worked");
if(counter>=count)
{
alert("Only " + count + " Phone number allowed.");
return false;
}
var htmlToAppend = '<tr id="pn'+ counter +'"><th>
<select class="phone_no">
<option value="home">home</option>
<option value="Business">Business</option>
<option value="Business2">Business 2</option>
</select>
</th>
<td><input type="text"/></td></tr>';
$("#phone_number").append ( htmlToAppend );
newTableRow.appendTo("#phone_number");
counter++;
});
$("#delete_phone").click(function()
{
if(counter==2)
{
alert("Cannot remove phone number");
return false;
}
counter--;
$("#pn" + counter-1).remove();
});
});
But the alert message alert("whoah it worked"); doesn't get displayed i.e its not entering the function.
<div class="info_type">
Phone numbers <hr>
<table id="phone_number">
<tr id="pn1">
<th>
<select class="phone_no">
<option value="home">home</option>
<option value="Business">Business</option>
<option value="Business2">Business 2</option>
</select>
</th>
<td><input type="text"/></td>
</tr>
</table>
<input type="button" id="add_phone" value="Add"/>
<input type="button" id="delete_phone" value="Delete"/>
</div>
I really want this solution. Can anybody help me??
PS: I am using Ruby on rails

Your string append is not well formed.
var htmlToAppend = '<tr id="pn'+ counter +'"><th><select class="phone_no"> <option value="home">home</option> <option value="Business">Business</option> <option value="Business2">Business 2</option></select> </th><td><input type="text"/></td></tr>';
Working sample in fiddle http://jsfiddle.net/shree/jNA4x/

try to rewrite htmlToAppend variable with a \n\ in the end of each line
demo

You can't have line breaks in your htmlToAppend variable,
var htmlToAppend = '<tr id="pn'+ counter +'"><th><select class="phone_no"><option value="home">home</option><option value="Business">Business</option><option value="Business2">Business 2</option></select></th><td><input type="text"/></td></tr>';
$("#phone_number").append ( htmlToAppend );
Example Code
A common pitfall for me as well.

increment the counter you did not increments it.
for more help use like the below example.
<html>
<h1>Add remove dynamically</h1>
<head>
<title></title>
</head>
<body>
Living in:
<table id="purchaseItems" name="purchaseItems" style="display: inline-table;">
<tr id="tr_1">
<td>
<input type="text" name="living_1" class="tbDescription next" required />
</td>
<td>
<input type="text" name="biggest_1" class="next" required />
</td>
<td>
<input type="text" name="nextbiggest_1" class="nextRow" required />
</td>
<td>
<input type="button" name="addRow[]" id="remove_1" class="removeRow" value='-' />
</td>
<td>
<input type="button" name="addRow[]" id="add_1" class="add" value='+' />
</td>
</tr>
</table>
</body>
</html>
<script type="text/javascript">
$("#remove_1").hide();
$(document).ready(function () {
$(document).on('click', '#purchaseItems .add', function () {
var total_row = $('#purchaseItems tr').length;
var rows = $('#purchaseItems tr').length+1;
if(total_row < 5)
{
// clear the values
$('#purchaseItems tr:last').after('<tr id="tr_'+rows+'"><td><input type="text" name="living_'+rows+'" id="living_'+rows+'" class="tbDescription next"></td><td><input type="text" name="biggest_'+rows+'" id="biggest_'+rows+'" class="next"></td><td><input type="text" name="nextbiggest_'+rows+'" id="nextbiggest_'+rows+'" class="nextRow"></td><td><input type="button" name="addRow[]" id="remove_'+rows+'" class="removeRow" value="-"></td><td><input type="button" name="addRow[]" id="add_'+rows+'" class="add" value="+"></td></tr>');
$(".add").hide();
$(".removeRow").show();
$("#add_"+rows).show();
}
else
{
alert("Maximum limit reached.")
}
});
$(document).on('keypress', '#purchaseItems .next', function (e) {
if (e.which == 13) {
var v = $(this).index('input:text');
var n = v + 1;
$('input:text').eq(n).focus();
//$(this).next().focus();
}
});
$(document).on('keypress', '#purchaseItems .nextRow', function (e) {
if (e.which == 13) {
$(this).closest('tr').find('.add').trigger('click');
$(this).closest('tr').next().find('input:first').focus();
}
});
$(document).on('click', '#purchaseItems .removeRow', function () {
var total_row = $('#purchaseItems tr').length;
if ($('#purchaseItems .add').length > 1) {
$(this).closest('tr').remove();
var last_tr_id = $('#purchaseItems tr:last').attr("id").split("_")[1];
$("#add_"+last_tr_id).show();
}
if ($('#purchaseItems .add').length == 1) {
$(".removeRow").hide();
}
});
});
</script>

Try this way using Jquery
<form id="myForm">
<div class="clonedInput">
<input type="text" class="phone_oa" id="textPhone1" name="input1" placeholder="Enter phone number" style="width: 110px;" />
<input type="button" name="btnDelete1" class="btnDel" value="Remove" disabled="disabled" />
</div>
<div id="addDelButtons" style="margin-top: 10px;">
<button type="button" id="btnAdd" class="btn" >Add Another Number</button>
</div>
</form>
Script
var inputs = 1;
$('#btnAdd').click(function() {
$('.btnDel:disabled').removeAttr('disabled');
var c = $('.clonedInput:first').clone(true);
c.children(':text').attr('name','input'+ (++inputs) ).val('');
c.children(':text').attr('id','textPhone'+ (inputs) ).val('');
c.children(':button').attr('name','btnDelete'+ (inputs) );
$('.clonedInput:last').after(c);
$('#btnAdd').attr('disabled',($('.clonedInput').length > 4));
});
$('.btnDel').click(function() {
if (confirm('Confirm delete?')) {
--inputs;
$(this).closest('.clonedInput').remove();
$('.btnDel').attr('disabled',($('.clonedInput').length < 2));
$('#btnAdd:disabled').removeAttr('disabled');
fixNames();
}
});
function fixNames(){
var i = inputs;
while(i--) {
$('input:text')[i].name = 'input'+ (i+1);
$('input:button')[i].name = 'btnDelete'+ (i+1);
}
}
DEMO

Related

How to change value inside input box that generated by jQuery?

please help me resolved this problem, I have an input value (weight) that generated by jQuery, I know it won't change it's value because of looping in my code, but is there another way to do this ?
The goal is I want to autogenerate the weight input value, but I can change it too.
if the snippet don't work, here's the link :
https://jsfiddle.net/s3grkqxm/
Thank you for your help.
var numRows = 2, ti = 5;
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function recalc() {
var berat = 0;
var qty = 0;
var grandtotal = 0;
var grandtotalbtg = 0;
$('#kas_table').find('tr').each(function() {
var berat = $(this).find('input.berat').val();
var qty = $(this).find('input.qty').val();
var subtotal = (berat * qty);
let berat_max = $(this).find('option:selected').data('berat');
$(this).find('input.subtotal').val(Math.round(subtotal * 100) / 100);
$(this).find('input.berat').val(berat_max).text();
});
}
$(function() {
$('div.table-responsive').on("keyup change blur", recalc);
});
var i=0;
$('#add_new').click(function(){
i++;
$('#mainbody').append('<tr><td>' +
'<select class="form-control nama" name="addmore['+i+'][nama]" id="nama'+i+'" required >' +
'<option disabled="disabled" selected="selected" value="" >Select Produk</option>' +
'<option value="1" data-berat="100">Item 1</option>' +
'<option value="1" data-berat="170">Item 2</option>' +
'</select></td>' +
'<td><input class="form-control qty" type="number" name="addmore['+i+'][qty]" id="qty'+i+'" required ></td>' +
'<td><input step=".001" class="form-control berat" type="number" name="addmore['+i+'][berat]" id="berat'+i+'" required ></td>' +
'<td><input class="form-control subtotal" type="number" name="addmore['+i+'][subtotal]" id="subtotal'+i+'" required readonly></td>'
)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="table-responsive">
<table class="table-bordered" width="100%" id="kas_table">
<thead>
<tr>
<th width="40%">Name</th>
<th width="10%">Qty</th>
<th width="10%">Weight</th>
<th>Subtotal KG</th>
<th>
<button id="add_new" type="button" name="add_new" class="btn btn-sm btn-success"> +</button>
</th>
</tr>
</thead>
<tbody id="mainbody">
<tr>
<td><select class="form-control nama" name="addmore[0][nama]" id="nama0" required >
<option disabled="disabled" selected="selected" value="" >Select Produk</option>
<option value="1" data-berat="100">Item 1</option>
<option value="2" data-berat="170">Item 2</option>
</select></td>
<td><input class="form-control qty" type="number" name="addmore[0][qty]" id=qty0 required></td>
<td><input step=".001" class="form-control berat" type="number" name="addmore[0][berat]" id="berat0" required></td>
<td><input class="form-control subtotal" type="number" name="addmore[0][subtotal]" id="subtotal0" readonly></td>
</tr>
</tbody>
</table>
</div>
the reason when you change Weight it back to the original value is because you refresh the whole table including the drop-down that's why it set back the value which must be set after the dropdown change.$('div.table-responsive').on("keyup change blur", recalc); due this.
you just need to separate each element change event to get the proper results.
I set the value in Weight on the change dropdown by adding this
$(document).on('change', 'select', function() {
$('#kas_table').find('tr').each(function() {
let berat_max = $(this).find('option:selected').data('berat');
$(this).find('input.berat').val(berat_max).text();
});
});
and separately call qty and weight using this
$('.qty').on("keyup change blur", recalc);
$('.berat').on("keyup change blur", recalc);
finally here is your updated code working as expected hope it will helpful for you.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
var numRows = 2, ti = 5;
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function recalc() {
var berat = 0;
var qty = 0;
var grandtotal = 0;
var grandtotalbtg = 0;
$('#kas_table').find('tr').each(function() {
var berat = $(this).find('input.berat').val();
var qty = $(this).find('input.qty').val();
var subtotal = (berat * qty);
$(this).find('input.subtotal').val(Math.round(subtotal * 100) / 100);
});
}
function selectProduct(e)
{
let berat_max = $(e).find('option:selected').data('berat');
$(e).parent().parent().find('input.berat').val(berat_max).text();
var berat = $(e).parent().parent().find('input.berat').val();
var qty = $(e).parent().parent().find('input.qty').val();
var subtotal = (berat * qty);
$(e).parent().parent().find('input.subtotal').val(Math.round(subtotal * 100) / 100);
}
$(function() {
$(document).on('change', 'select', function() {
$('.qty').on("keyup change blur", recalc);
$('.berat').on("keyup change blur", recalc);
});
var i=0;
$('#add_new').click(function(){
i++;
$('#mainbody').append('<tr><td>' +
'<select class="form-control nama" name="addmore['+i+'][nama]" id="nama'+i+'" onchange="selectProduct(this)" required >' +
'<option disabled="disabled" selected="selected" value="">Select Produk</option>' +
'<option value="1" data-berat="100">Item 1</option>' +
'<option value="1" data-berat="170">Item 2</option>' +
'</select></td>' +
'<td><input class="form-control qty" type="number" name="addmore['+i+'][qty]" id="qty'+i+'" required ></td>' +
'<td><input step=".001" class="form-control berat" type="number" name="addmore['+i+'][berat]" id="berat'+i+'" required ></td>' +
'<td><input class="form-control subtotal" type="number" name="addmore['+i+'][subtotal]" id="subtotal'+i+'" required readonly></td>'
)
});
});
</script>
</head>
<body>
<div class="table-responsive">
<table class="table-bordered" width="100%" id="kas_table">
<thead>
<tr>
<th width="40%">Name</th>
<th width="10%">Qty</th>
<th width="10%">Weight</th>
<th>Subtotal KG</th>
<th>
<button id="add_new" type="button" name="add_new" class="btn btn-sm btn-success"> +</button>
</th>
</tr>
</thead>
<tbody id="mainbody">
<tr>
<td><select class="form-control nama" name="addmore[0][nama]" id="nama0" onchange="selectProduct(this)" required >
<option disabled="disabled" selected="selected" value="">Select Produk</option>
<option value="1" data-berat="100">Item 1</option>
<option value="2" data-berat="170">Item 2</option>
</select></td>
<td><input class="form-control qty" type="number" name="addmore[0][qty]" id=qty0 required></td>
<td><input step=".001" class="form-control berat" type="number" name="addmore[0][berat]" id="berat0" required></td>
<td><input class="form-control subtotal" type="number" name="addmore[0][subtotal]" id="subtotal0" readonly></td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

Show all names found in table when click display button

I need to show all names found in table #tb and display as list using jQuery when the user clicks the display button.
My code is below. I can add successfully, but how can I take data from column name and show as list?
#{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<script src="~/Scripts/jquery-1.10.2.js"></script>
<script>
$(function () {
$("#btn").click(function() {
var x = $("#txt1").val();
var y = $("#txt2").val();
var z = $("#mycountry").val();
$("#tb").append("<tr> <td>" + x + "</td> <td>" + y + "</td> <td>" + z + "</td><td> <input type='button'class='c' value='Delete'/></td><td> <input type='button' class='d' value='Edit'/></td></tr>");
});
$("#tb").on("click", ".c", function () {
//$(this).parent().parent().remove();
$(this).closest('tr').remove();
});
$("#tb").on("click", ".d", function () {
var row = $(this).closest('tr').toggleClass("editing");
row.find("td").slice(0, 3).prop("contenteditable", row.hasClass("editing"));
});
});
</script>
<style>
.editing {
background: yellow;
}
</style>
</head>
<body>
<div>
ID
<input type="text" id="txt1" /><br />
Name
<input type="text" id="txt2" /><br />
Country:
<select id="mycountry">
<option>---select---</option>
<option>Egypt</option>
<option>qatar</option>
<option>saudia</option>
<option>emarates</option>
</select><br />
<input type="button" value="add" id="btn" />
<input type="button" value="display" id="btndis" />
<table>
<thead>
<tr>
<td>
ID
</td>
<td>
Name
</td>
<td>
Country
</td>
<td>
</tr>
</thead>
<tbody id="tb"></tbody>
</table>
</div>
</body>
</html>
Try this:
https://jsfiddle.net/ionutmihai1995/euk6xkzp/
$('#btndis').click(function(){
$('ul').empty();
$("#tb").find('tr').each(function(i,el){
var $tds = $(this).find('td');
//for name
$('ul').append("<li>"+$tds.eq(1).text()+"</li>");
});
});
Please check below code.
$("#btndis").on('click',function(){
$("body").append("<ul id='listNames''></ul>");
$('#tb td:nth-child(2)').each(function() {
$("#listNames").append("<li>"+$(this).text()+"</li>")
});
})
Please refer code on this Link. https://jsfiddle.net/gq5f5ux2/2/
On click of the display button iterate loop through all the tr>td-second child to get all the names and then append a UL and LI in the body to display list all the names.
Add a class for colum called "name" and then you can iterate over and select the text in the element
<td class="name">John</td>
Then in JQuery:
$(document).ready(function() {
$('#tb').find('tr').each(function() {
var name = $(this).find('.name').text();
$('#result').append('<p>'+name+'</p>');
});
});
Working example
check this JsFiddle Demo
HTML
<div>
ID
<input type="text" id="txt1" />
<br /> Name
<input type="text" id="txt2" />
<br /> Country:
<select id="mycountry">
<option>---select---</option>
<option>Egypt</option>
<option>qatar</option>
<option>saudia</option>
<option>emarates</option>
</select>
<br />
<input type="button" value="add" id="btn" />
<input type="button" value="display" id="btndis" />
<table>
<thead>
<tr>
<td>
ID
</td>
<td>
Name
</td>
<td>
Country
</td>
<td>
</tr>
</thead>
<tbody id="tb"></tbody>
</table>
<ul id="ulNames">
</ul>
</div>
JS
$(function() {
$("#btn").click(function() {
var x = $("#txt1").val();
var y = $("#txt2").val();
var z = $("#mycountry").val();
$("#tb").append("<tr> <td>" + x + "</td> <td>" + y + "</td> <td>" + z + "</td><td> <input type='button'class='c' value='Delete'/></td><td> <input type='button' class='d' value='Edit'/></td></tr>");
});
$("#tb").on("click", ".c", function() {
//$(this).parent().parent().remove();
$(this).closest('tr').remove();
});
$("#tb").on("click", ".d", function() {
var row = $(this).closest('tr').toggleClass("editing");
row.find("td").slice(0, 3).prop("contenteditable", row.hasClass("editing"));
});
$('#btndis').on('click', function() {
//gets table
var oTable = document.getElementById('tb');
//gets rows of table
var rowLength = oTable.rows.length;
//loops through rows
for (i = 0; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
// get your cell info here
var cellVal = oCells.item(1).innerHTML;
$('#ulNames').append('<li>' + cellVal + '</li>');
}
});
});
CSS
.editing {
background: yellow;
}
$("#btndis").click(function() {
$("body").append("ul");
for(var i = 1; i <= $("tr > td").length; i++) {
$("ul").append("li").addClass("li.li-"+i);
$("li.li-"+i).append($("td:nth-child("+i+")").text());
}
}
Explanation :
First, we create the ul to store data. Then, we iterate each tr child (td) with a for loop, we create a li and store data into it. It will be displayed in a list, as asked.

Add selected options value into an array in javascript

I have 2 multiple select boxes where I select some of the options and add it to the other select box. When i click on save, the selected option values should be stored into one array and passed to the home controller. when i put alert i get the proper data but I get the below error in firebug console which i'm not able to solve it.Plse help me in this regard. here is the error and code.
for (var i = 0; i <= PairedSelectBox.options.length; i++) {
selectedClientChips.push(PairedSelectBox.options[i].value);
alert("selectedClientChips == " + selectedClientChips);
}
I get the error in console like this
TypeError: PairedSelectBox.options[i] is undefined
selectedClientChips.push(PairedSelectBox.options[i].value);
This is the html code:
<table>
<tr>
<td>
<label style="font-size: medium;">Client Chip details</label>
</td>
</tr>
<tr>
<td>
<label>Search</label>
<input type="text" id="searchId">
<input type="button" value="Go" onclick="getClientChipDetails();"></td>
</tr>
<tr>
<td>
<label style="font-size: small;">Client-Chip data</label>
</td>
<td></td>
<td>
<label style="font-size: small">Selected Client-Chip data</label>
</td>
</tr>
<tr>
<td>
<select id="MasterSelectBox" name="MasterSelectBox" size="10" multiple="multiple"></select>
</td>
<td>
<button id="btnAdd">> </button>
<br>
<button id="btnRemove">< </button>
</td>
<td>
<select id="PairedSelectBox" name="PairedSelectBox" size="10" multiple="multiple">
</select>
</td>
</tr>
</table>
This is the script:
$(document).ready(function () {
$('#MasterSelectBox').pairMaster();
$('#btnAdd').click(function () {
$('#MasterSelectBox').addSelected('#PairedSelectBox');
});
$('#btnRemove').click(function () {
$('#PairedSelectBox').removeSelected('#MasterSelectBox');
});
});
Try this. I modify your code.
HTML
<table>
<tr><td>Master select box</td><td>Paired select box</td></tr>
<tr>
<td>
<select id="MasterSelectBox" name="MasterSelectBox" size="10" multiple="multiple">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
</td>
<td>
<button id="btnAdd"> > </button><br>
<button id="btnRemove"> < </button>
</td>
<td>
<select id="PairedSelectBox" name="PairedSelectBox" size="10" multiple="multiple"></select>
</td>
</tr>
</table>
<button id="save">Save</button>
<p id="output"></p>
Javascript
$(document).ready( function(){
$('#MasterSelectBox').pairMaster();
$('#btnAdd').click(function(){
$('#MasterSelectBox').addSelected('#PairedSelectBox');
});
$('#btnRemove').click(function(){
$('#PairedSelectBox').removeSelected('#MasterSelectBox');
});
$( "#save" ).click( function( e ) {
$( "#output" ).empty();
$.each( $( "#PairedSelectBox" ).val(), function( i, v ) {
$( "#output" ).append( $( "<span> " + v + " </span>" ) );
} );
} );
});
P.S. and use rawgit.com links to libraries, not raw.githubusercontent.com to attach scripts to jsfiddle.
#madhu i had update your code on jsfiddle with following code...
$(document).ready( function(){
var data=[];
//$('#MasterSelectBox').pairMaster();
$('#btnAdd').click(function(){
$("#MasterSelectBox option:selected").each(function () {
var selText = $(this).val();
data.push(selText);
});
$.each(data, function(val, text) {
$('#PairedSelectBox').append( $('<option>').text(text).attr('value',text));
});
});
$('#save_btn').click(function(){
alert("your data is"+JSON.stringify(data));
});
});
check your jsfiddle link
I got it... I had nott delcard the pairedSelectBox.
var PairedSelectBox = document.getElementById("PairedSelectBox");
// alert("PairedSelectBox==="+ PairedSelectBox);
for (var i = 0; i<PairedSelectBox.options.length; i++) {
selectedClientChips.push(PairedSelectBox.options[i].value);
//alert("selectedClientChips == " + selectedClientChips);
}
alert("selectedClientChips==="+selectedClientChips);

Calculate on change for each row

I have an invoice form to generate a PDF. I want to calculate the inputs after the change of the value that the user fills in the form.
I can calculate the first row, but i want to (1) calculate each row and at the end to (2) calculate all the colums properly. For the first step just to the (1) and i will make the total calculation.
The problem is that i generate the rows with dynamic name and id because i post them in an array to the database. For this example the id is the same for every row of inputs.
PS: i cannot make .change work and i use $(document).on('change', '#qty', function (e) { calculateLine(); }); to trigger the calculation function for each input. I dont know why .change is not working as it support to, with latest jquery.
[invoice.php]
<script>
$(document).ready(function () {
$(document).on('change', '#qty', function (e) { calculateLine(); });
$(document).on('change', '#price', function (e) { calculateLine(); });
$(document).on('change', '#discount', function (e) { calculateLine(); });
$(document).on('change', '#discountPrice', function (e) { calculateLine(); });
});
</script>
[invoice.js]
function calculateLine() {
var qty = parseFloat($('#qty').val());
var price = parseFloat($('#price').val());
var discount = parseFloat($('#discount').val());
var discountPrice = parseFloat($('#discountPrice').val());
var vat = parseFloat($('#vat').val());
var netTotal = 0;
var total = 0;
var vatAmount = 0;
if (!qty && qty == 0) {
return;
}
if (!price && price == 0) {
return;
}
netTotal = qty * price;
if ((!discount || discount == 0) && discountPrice != 0) {
discount = (discountPrice / netTotal) * 100;
}
if ((!discountPrice || discountPrice == 0) && discount != 0) {
discountPrice = (netTotal / 100) * discount;
}
if (discountPrice != 0 && discount != 0) {
discountPrice = (netTotal / 100) * discount;
}
if ((!discount || discount == 0) && (!discountPrice || discountPrice == 0)) {
discountPrice = 0;
discount = 0;
}
total = netTotal - discountPrice;
if (!total || total == 0) {
total = 0;
}
vatAmount = (total / 100) * vat;
$('#total').val(total);
$('#discount').val(discount);
$('#discountPrice').val(discountPrice);
$('#vatAmount').val(vatAmount);
//calculateTotal();
}
[html]
<tr>
<td class="col-xs-0">
<input type="checkbox" name="selected[]" class="checkall">
</td>
<td class="col-xs-5">
<textarea type="text" name="invoice[item][{{j}}][description]" class="form-control description" rows="1" ></textarea>
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][unit]" class="form-control unit" value="" />
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][qty]" class="form-control qty" value="" />
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][price]" class="form-control price" value="" />
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][discount]" class="form-control discount" value="" >
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][discountPrice]" class="form-control discountPrice" />
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][total]" class="form-control total" value="" />
</td>
<td class="col-xs-1">
<input type="text" name="invoice[item][{{j}}][vat]" class="form-control vat" value="{{invcl_vat}}" readonly />
<input type="hidden" name="invoice[item][{{j}}][vatAmount]" class="form-control vatAmount" value="" readonly />
</td>
</tr>
You haven't shown your HTML, but it's clear from your question that you're using the same id (qty, etc.) on more than one element. You can't do that. Every id must be unique on the page. In this case, you'd probably use classes instead.
The general way that you do what you're talking about is indeed to use delegated event handling, then find the containing row, and use that as the starting point looking for descendant inputs using classes rather than ids:
$("selector-for-the-table").on("change", "input", function() {
// Get the row containing the input
var row = $(this).closest("tr");
// Get the values from _this row's_ inputs, using `row.find` to
// look only within this row
var qty = parseFloat(row.find('.qty').val());
var price = parseFloat(row.find('.price').val());
var discount = parseFloat(row.find('.discount').val());
var discountPrice = parseFloat(row.find('.discountPrice').val());
var vat = parseFloat(row.find('.vat').val());
// ...
});
I've also rooted that on the table, rather than document, so it only applies where appropriate.
Live (Simplified) Example:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="qty"></td>
<td><input type="text" class="price"></td>
<td><input type="text" class="total" disabled></td>
</tr>
<!-- ...and so on... -->
</tbody>
</table>
<script>
(function() {
"use strict";
$("table").on("change", "input", function() {
var row = $(this).closest("tr");
var qty = parseFloat(row.find(".qty").val());
var price = parseFloat(row.find(".price").val());
var total = qty * price;
row.find(".total").val(isNaN(total) ? "" : total);
});
})();
</script>
</body>
</html>
You've said before that the names are dynamic. Surely there is some characteristic of the fields you're trying to find that is consistent, or you can make them consistent. In the worst case (and I mean in the worst case), you could do something based on position — the first input in the row is row.find("input:eq(0)"), the second is row.find("input:eq(1)"), and so on.
Live Example Using eq:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset="utf-8">
<title>Example</title>
</head>
<body>
<table>
<thead>
<tr>
<th>Quantity</th>
<th>Price</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text"></td>
<td><input type="text"></td>
<td><input type="text" disabled></td>
</tr>
<!-- ...and so on... -->
</tbody>
</table>
<script>
(function() {
"use strict";
$("table").on("change", "input", function() {
var row = $(this).closest("tr");
var qty = parseFloat(row.find("input:eq(0)").val());
var price = parseFloat(row.find("input:eq(1)").val());
var total = qty * price;
row.find("input:eq(2)").val(isNaN(total) ? "" : total);
});
})();
</script>
</body>
</html>
But avoid that if you possibly can, it's fragile — if you change the order of columns, you have to change your code.

not able to resolve form.all_skill is undefined in javascript

My javascript code is
function addTaskSkill(form) {
var at = form.all_skill.length -1;
var td = form.task_skill.length -1;
var tasks = "x";
if(td>=0 && form.task_skill.options[0].value==skll_id){
form.task_skill.options[0] = null;
td = form.task_skill.length -1;
}
for (td; td > -1; td--) {
tasks = tasks + "," + form.task_skill.options[td].value + ","
}
for (at; at > -1; at--) {
if (form.all_skill.options[at].selected && tasks.indexOf("," + form.all_skill.options[at].value + ",") == -1) {
t = form.task_skill.length
opt = new Option(form.all_skill.options[at].text, form.all_skill.options[at].value);
form.task_skill.options[t] = opt
}
}
//checkForTaskSkill(form.task_skill);
}
function removeTaskSkill(form) {
td = form.task_skill.length -1;
for (td; td > -1; td--) {
if (form.task_skill.options[td].selected) {
form.task_skill.options[td] = null;
}
}
}
And My calling function is
<form action="#" method="post" name="detailFrm">
<table>
<tr>
<td>
<select name="all_skill" size="10" class="span5" multiple="multiple" >
<option value="30">Apache</option>
<option value="31">Microsoft IIS</option>
<option value="32">Tomcat</option>
<option value="34">JBoss</option>
<option value="35">BEA WebLogic</option>
</select>
</td>
<td><input type="button" class="btn" value=">" onclick="javascript:addTaskSkill(document.detailFrm)" />
<br><br><input type="button" class="btn" value="<"
onclick="javascript:removeTaskSkill(document.detailFrm)" /></td>
<td>
<select name="task_skill" class="span5" size="10" multiple="multiple"> </select>
</td>
</tr>
</table>
</form>
Here i am selecting some option from one selectbox & on clicking >> it should push to next selectbox. the error i am getting is
TypeError: form.all_skill is undefined
[Break On This Error]
var at = form.all_skill.length -1;
I am not getting the solution for this. Please help here to get the solution. i am trying to make a listbox swapper.
Thanks in advance.
To reference the elements of a form you can either use the form elements selection like this:
form.elements['all_skill'] // where form is: document.detailFrm
Or you use an ID:
//HTML
<select name="all_skill" id="all_skill" size="10" class="span5" multiple="multiple" >
// in JS
document.getElementById('all_skill');

Categories

Resources