Adding variable value on onchange event - javascript

I have a table and i am adding new row through javascript and adding an event on new row as well but it's not working.
Here is my code:
function moreitem() {
document.getElementById('tottr').value = parseInt(document.getElementById('tottr').value) + 1;
ain = document.getElementById('tottr').value;
$('#mytable tbody tr:last')
.after("<tr><td><select name='pid[]' id='' class='form-control' onchange='getstock(this.value,'st" + ain + "','pc" + ain + "')'><option value=''>Select Product</option><option value='1'>Drink</option></select></td><td><input type='text' id='st" + ain + "' placeholder='Available Stock' class='form-control'></td><td><input type='text' id='qty" + ain + "' onchange='gettot(this.value,ain)' name='qty[]' placeholder='Quantity' class='form-control'></td><td><input type='text' id='pc" + ain + "' name='pprice[]' placeholder='Per Piece Price' class='form-control'></td><td><input type='text' name='tprice[]' placeholder='Total Price' id='tp" + ain + "' class='form-control'></td></tr>");
}
function getstock(inval, stid, pcid) {
$.ajax({
url: "getprice.php",
data: "inval=" + inval + "&stid=" + stid + "&pcid=" + pcid,
type: "post",
success: function(e) {
// alert(e);
$('#hide').html(e);
}
})
// alert(inval);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="mytable" class="table table-bordered table-striped">
<thead>
<tr>
<th>Product</th>
<th>Stock</th>
<th>Qty.</th>
<th>Amount Per Piece</th>
<th>Total Amount</th>
</tr>
</thead>
<tbody>
<tr id="tr1">
<td>
<select name="pid[]" id="" class="form-control" onchange="getstock(this.value,'st1','pc1')">
<option value="1">hello</option>
<option value="2">Hello2</option>
</select>
</td>
<td><input type="text" id="st1" placeholder="Available Stock" class="form-control"></td>
<td><input type="text" id="qty1" onchange="gettot(this.value,1)" name="qty[]" placeholder="Quantity" class="form-control"></td>
<td><input type="text" id="pc1" name="pprice[]" placeholder="Per Piece Price" class="form-control"></td>
<td><input type="text" name="tprice[]" placeholder="Total Price" id="tp1" class="form-control"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
Add More Item
</td>
</tr>
</tfoot>
</table>
<input type="hidden" id="tottr" value="1">
getstock is working for the first row but not for other rows and when i inspect the select dropdown it shows below:
onchange="getstock(this.value," st2','pc2')'="">

Don't do so messy while using parameterize function with html string.
make it simple and pass it to function.
something like below
var stvar="st"+ain;
var pcvar="pc"+ain;
var ain = 1
function moreitem() {
document.getElementById('tottr').value = parseInt(document.getElementById('tottr').value) + 1;
ain = document.getElementById('tottr').value;
var stvar = "st" + ain;
var pcvar = "pc" + ain;
$('#mytable tbody tr:last').after("<tr><td><select name='pid[]' id='sel_"+ain+"' class='form-control'><option value=''>Select Product</option><option value='1'>Drink</option></select></td><td><input type='text' id='st" + ain + "' placeholder='Available Stock' class='form-control'></td><td><input type='text' id='qty" + ain + "' onchange='gettot(this.value,ain)' name='qty[]' placeholder='Quantity' class='form-control'></td><td><input type='text' id='pc" + ain + "' name='pprice[]' placeholder='Per Piece Price' class='form-control'></td><td><input type='text' name='tprice[]' placeholder='Total Price' id='tp" + ain + "' class='form-control'></td></tr>");
$("#sel_"+ain).on("change",function(){
getstock($(this).val(), stvar, pcvar)
})
}
function getstock(v, s, p) {
console.log(v)
console.log(s)
console.log(p)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="mytable" class="table table-bordered table-striped">
<thead>
<tr>
<th>Product</th>
<th>Stock</th>
<th>Qty.</th>
<th>Amount Per Piece</th>
<th>Total Amount</th>
</tr>
</thead>
<tbody>
<tr id="tr1">
<td>
<select name="pid[]" id="" class="form-control" onchange="getstock(this.value,'st1','pc1')">
<option value="1">hello</option>
<option value="2">Hello2</option>
</select>
</td>
<td><input type="text" id="st1" placeholder="Available Stock" class="form-control"></td>
<td><input type="text" id="qty1" onchange="gettot(this.value,1)" name="qty[]" placeholder="Quantity" class="form-control"></td>
<td><input type="text" id="pc1" name="pprice[]" placeholder="Per Piece Price" class="form-control"></td>
<td><input type="text" name="tprice[]" placeholder="Total Price" id="tp1" class="form-control"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
Add More Item
</td>
</tr>
</tfoot>
</table>
<input type="hidden" id="tottr" value="1">

I think the single quote before getstock and before st2 gets confused. You can escape and print double quotes for onchange event so that the inside single quote and outside double quotes doesn't get confused. I hope the below code helps.
function moreitem(){ document.getElementById('tottr').value=parseInt(document.getElementById('tottr').value)+1;
ain=document.getElementById('tottr').value;
$('#mytable tbody tr:last').after("<tr><td><select name='pid[]' id='' class='form-control' onchange=\"getstock(this.value,'st"+ain+"','pc"+ain+"')\"><option value=''>Select Product</option><option value='1'>Drink</option></select></td><td><input type='text' id='st"+ain+"' placeholder='Available Stock' class='form-control'></td><td><input type='text' id='qty"+ain+"' onchange='gettot(this.value,ain)' name='qty[]' placeholder='Quantity' class='form-control'></td><td><input type='text' id='pc"+ain+"' name='pprice[]' placeholder='Per Piece Price' class='form-control'></td><td><input type='text' name='tprice[]' placeholder='Total Price' id='tp"+ain+"' class='form-control'></td></tr>");
}
function getstock(inval,stid,pcid){
$.ajax({
url:"getprice.php",
data:"inval="+inval+"&stid="+stid+"&pcid="+pcid,
type:"post",
success:function(e){
// alert(e);
$('#hide').html(e);
}
})
// alert(inval);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="mytable" class="table table-bordered table-striped">
<thead>
<tr>
<th>Product</th>
<th>Stock</th>
<th>Qty.</th>
<th>Amount Per Piece</th>
<th>Total Amount</th>
</tr>
</thead>
<tbody>
<tr id="tr1">
<td>
<select name="pid[]" id="" class="form-control" onchange="getstock(this.value,'st1','pc1')">
<option value="1">hello</option>
<option value="2">Hello2</option>
</select>
</td>
<td><input type="text" id="st1" placeholder="Available Stock" class="form-control"></td>
<td><input type="text" id="qty1" onchange="gettot(this.value,1)" name="qty[]" placeholder="Quantity" class="form-control"></td>
<td><input type="text" id="pc1" name="pprice[]" placeholder="Per Piece Price" class="form-control"></td>
<td><input type="text" name="tprice[]" placeholder="Total Price" id="tp1" class="form-control"></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5">
Add More Item
</td>
</tr>
</tfoot>
</table>
<input type="hidden" id="tottr" value="1">

Related

How to get multiple row total by type

In the light of the code below, I want the return type to have a separate total and if the sales will be the result of the total sales input. In the meantime, the whole Total is going to Sales Total. Below are 2 roads as an example. There will be many more rows like this, each of which will have a type of sales / return. The following two inputs will fill up accordingly.
var grandTotal = 0;
$("input[name='qty[]']").each(function(index) {
var qty = $("input[name='qty[]']").eq(index).val();
var price = $("input[name='price[]']").eq(index).val();
var total = parseFloat(parseFloat(qty) * parseFloat(price)).toFixed(2);
if (!isNaN(total)) {
$("input[name='sub_total[]']").eq(index).val(total);
grandTotal = parseFloat(parseFloat(grandTotal) + parseFloat(total)).toFixed(2);
$('#total').val(grandTotal);
}
})
<script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script>
<div onload="add_calcualte ()">
<table border="1">
<thead>
<tr>
<th>Type</th>
<th>Product</th>
<th>Quantity</th>
<th>Price </th>
<th>Sub Total</th>
</tr>
<tr>
<td>
<select name='type[]'>
<option value="Sale"> Sale</>
<option value="Retrun"> Retrun</>
</select>
</td>
<td><input name='product_name[]' value='Mobile' ></td>
<td><input type='text' name='qty[]' class='qty' value='5'></td>
<td><input type='number' name='price[]' class='price' value='15000'></td>
<td><input type='number' name='sub_total[]' class='sub_total'></td>
</tr>
<tr>
<td>
<select name='type[]'>
<option value="Retrun"> Retrun</>
<option value="Sale"> Sale</>
</select>
</td>
<td><input name='product_name[]' value='Headphone' ></td>
<td><input type='text' name='qty[]' class='qty' value='1'></td>
<td><input type='number' name='price[]' class='price' value='1200'></td>
<td><input type='number' name='sub_total[]' class='sub_total'></td>
</tr>
</thead>
</table>
<br>
Sales TOTAL:
<input class="form-control text-right" readonly type="text" id="total" name="total">
<hr>
Return TOTAL:
<input class="form-control text-right" readonly type="text" id="return" name="return">
</div>
You could do something like this:
function getTotals() {
var total = $("select option[value=Sale]:selected").closest("tr").map(function() {
return $(this).find(".sub_total").val()
}).get().reduce((a, b) => {
return +a + +b
})
$("#total").val(total)
var _return = $("select option[value=Return]:selected").closest("tr").map(function() {
return $(this).find(".sub_total").val()
}).get().reduce((a, b) => {
return +a + +b
})
$("#return").val(_return)
}
Also I assume <option value="Retrun"> Retrun</> should be <option value="Return"> Return</option>
Demo
$("input[name='qty[]']").each(function(index) {
var qty = $("input[name='qty[]']").eq(index).val();
var price = $("input[name='price[]']").eq(index).val();
var total = parseFloat(parseFloat(qty) * parseFloat(price)).toFixed(2);
if (!isNaN(total)) {
$("input[name='sub_total[]']").eq(index).val(total);
getTotals();
}
})
function getTotals() {
var total = $("select option[value=Sale]:selected").closest("tr").map(function() {
return $(this).find(".sub_total").val()
}).get().reduce((a, b) => {
return +a + +b
})
$("#total").val(total)
var _return = $("select option[value=Return]:selected").closest("tr").map(function() {
return $(this).find(".sub_total").val()
}).get().reduce((a, b) => {
return +a + +b
})
$("#return").val(_return)
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js" crossorigin="anonymous"></script>
<div onload="add_calcualte ()">
<table border="1">
<thead>
<tr>
<th>Type</th>
<th>Product</th>
<th>Quantity</th>
<th>Price </th>
<th>Sub Total</th>
</tr>
<tr>
<td>
<select name='type[]'>
<option value="Sale"> Sale
</option>
<option value="Return"> Retrun
</option>
</select>
</td>
<td><input name='product_name[]' value='Mobile'></td>
<td><input type='text' name='qty[]' class='qty' value='5'></td>
<td><input type='number' name='price[]' class='price' value='15000'></td>
<td><input type='number' name='sub_total[]' class='sub_total'></td>
</tr>
<tr>
<td>
<select name='type[]'>
<option value="Return"> Retrun
</option>
<option value="Sale"> Sale
</option>
</select>
</td>
<td><input name='product_name[]' value='Headphone'></td>
<td><input type='text' name='qty[]' class='qty' value='1'></td>
<td><input type='number' name='price[]' class='price' value='1200'></td>
<td><input type='number' name='sub_total[]' class='sub_total'></td>
</tr>
<tr>
<td>
<select name='type[]'>
<option value="Return"> Retrun
</option>
<option value="Sale"> Sale
</option>
</select>
</td>
<td><input name='product_name[]' value='Headphone'></td>
<td><input type='text' name='qty[]' class='qty' value='1'></td>
<td><input type='number' name='price[]' class='price' value='1200'></td>
<td><input type='number' name='sub_total[]' class='sub_total'></td>
</tr>
</thead>
</table>
<br> Sales TOTAL:
<input class="form-control text-right" readonly type="text" id="total" name="total">
<hr> Return TOTAL:
<input class="form-control text-right" readonly type="text" id="return" name="return">
</div>

How to make dynamic table column in javascript using select option

How to if the teacher select Items (4) using JavaScript,
as you can see, the table row adjust, it depends on what Items that the user selected,
please help me guys
here's the example:
if the user select Items (3)
here is my html
<table class="tableattrib" id="myTables">
<tr>
<td colspan="1" class="tdhead1">Class</td>
<td colspan="20" class="tdcell">
<select>
<option>Grading Categories</option>
</select>
<select onchange="myFunction()">
<option>Items</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select>
<option>Section</option>
</select>
</td>
</tr>
<tr>
<td class="tdnb" colspan="21"><input id="myInput" type="text" placeholder="Search Student" class="search"></td>
</tr>
<tr>
<td colspan="1" class="tdhead">Student Name</td>
<td class="tdcell1"><input type="text" name="" id="datepicker" placeholder="mm/dd/yyyy" title="Quiz Date"/></td>
<td class="tdcell1"><input type="text" name="" id="datepicker1" placeholder="mm/dd/yyyy" title="Quiz Date"/></td>
<td class="tdcell1"><input type="text" name="" id="datepicker2" placeholder="mm/dd/yyyy" title="Quiz Date"/></td>
<td class="tdcell2">Average</td>
</tr>
<tbody id="myTable">
<tr id="myRow">
<td colspan="1" class="tdcell">Marvin Makalintal</td>
<td class="tdcell1"><input type="text" name=""/></td>
<td class="tdcell1"><input type="text" name=""/></td>
<td class="tdcell1"><input type="text" name=""/></td>
<td class="tdcell1"><input type="text" name=""/></td>
</tr>
<tr>
<td class="tdbtn" colspan="21"><button type="button" class="save">&plus; Save</button>
<button type="button" class="save">&check; Finalize</button></td>
</tr>
</tbody>
</table>
</body>
<script>
function myFunction() {
var row = document.getElementById("myRow");
var x = row.insertCell(1);
x.innerHTML = "New cell";
}
</script>
First, we pass this.value into myFunction.
- <select onchange="myFunction()">
+ <select onchange="myFunction(this.value)">
Next, we add id="headerRow" to the header row.
- <tr>
+ <tr id="headerRow">
<td colspan="1" class="tdhead">Student Name</td>
Then, we implement configureRow(row, numItems, innerHTMLFunc) to insert and delete cells.
Finally, we call configureRow in myFunction.
function configureRow(row, numItems, innerHTMLFunc) {
var numCells = numItems + 2;
while (row.childElementCount < numCells) {
var x = row.insertCell(row.childElementCount - 1);
x.innerHTML = innerHTMLFunc(row.childElementCount - 2);
}
while (row.childElementCount > numCells) {
row.deleteCell(row.childElementCount - 2);
}
}
function myFunction(numItems) {
numItems = Number(numItems);
var row = document.getElementById("headerRow");
configureRow(row, numItems, (itemNum) => `<td class="tdcell1"><input type="text" name="" id="datepicker${itemNum - 1 || ''}" placeholder="mm/dd/yyyy" title="Quiz Date" /></td>`);
var row = document.getElementById("myRow");
configureRow(row, numItems, (itemNum) => '<td class="tdcell1"><input type="text" name=""></td>');
}
<table class="tableattrib" id="myTables">
<tr>
<td colspan="1" class="tdhead1">Class</td>
<td colspan="20" class="tdcell">
<select>
<option>Grading Categories</option>
</select>
<select onchange="myFunction(this.value)">
<option>Items</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select>
<option>Section</option>
</select>
</td>
</tr>
<tr>
<td class="tdnb" colspan="21"><input id="myInput" type="text" placeholder="Search Student" class="search"></td>
</tr>
<tr id="headerRow">
<td colspan="1" class="tdhead">Student Name</td>
<td class="tdcell1"><input type="text" name="" id="datepicker" placeholder="mm/dd/yyyy" title="Quiz Date" /></td>
<td class="tdcell1"><input type="text" name="" id="datepicker1" placeholder="mm/dd/yyyy" title="Quiz Date" /></td>
<td class="tdcell1"><input type="text" name="" id="datepicker2" placeholder="mm/dd/yyyy" title="Quiz Date" /></td>
<td class="tdcell2">Average</td>
</tr>
<tbody id="myTable">
<tr id="myRow">
<td colspan="1" class="tdcell">Marvin Makalintal</td>
<td class="tdcell1"><input type="text" name="" /></td>
<td class="tdcell1"><input type="text" name="" /></td>
<td class="tdcell1"><input type="text" name="" /></td>
<td class="tdcell1"><input type="text" name="" /></td>
</tr>
<tr>
<td class="tdbtn" colspan="21"><button type="button" class="save">&plus; Save</button>
<button type="button" class="save">&check; Finalize</button></td>
</tr>
</tbody>
</table>
<!DOCTYPE html>
<html>
<head></head>
<body>
<script>
function myFunction() {
alert(selectionnumber);
var intselectionnumber = 0;
intselectionnumber =document.getElementById("selectionnumber").value;
alert(intselectionnumber);
var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i] ; i++) {
//iterate through rows
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
if (j == 1) {
for ( k = 1; k <= intselectionnumber; k++)
{
var x = row.insertCell(j);
x.innerHTML = "<input type='text' name='' id='datepicker2' placeholder='mm/dd/yyyy' title='Quiz Date'/>";
}
}
}
}
}
</script>
<h1>The onclick Event</h1>
<table class="tableattrib" id="myTables">
<tr>
<td colspan="1" class="tdhead1">Class</td>
<td colspan="20" class="tdcell">
<select>
<option>Grading Categories</option>
</select>
<select id='selectionnumber' onchange="myFunction();">
<option value="0">Items</option>
<option value="1" selected='selected'>1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
<select>
<option>Section</option>
</select>
</td>
</tr>
</table>
<table id='mytab1'>
<tr>
<td class="tdnb" colspan="21"><input id="myInput" type="text" placeholder="Search Student" class="search"></td>
</tr>
<tr>
<td colspan="1" class="tdhead">Student Name</td>
<td class="tdcell2">Average</td>
</tr>
<tr id="myRow">
<td colspan="1" class="tdcell">Marvin Makalintal</td>
<td class="tdcell1"><input type="text" name="" /></td>
</tr>
<tr>
<td class="tdbtn" colspan="21">
<button type="button" class="save">&plus; Save</button>
<button type="button" class="save">&check; Finalize</button>
</td>
</tr>
</table>
</body>
</html>

How to calculate sum of one field in table and put it in an input

I have a table in razor and I sent the data by ViewBag from controller
<table>
<thead>
<tr>
<th>Name</th>
<th>Category</th>
<th>Price</th>
<th>Count</th>
</tr>
</thead>
<tbody>
#foreach(var item in ViewBag.Products)
{
<tr>
<td>#item.Name</td>
<td>#item.Category</td>
<td>
<input type="text" class="form-control" value="#item.Price" />
</td>
<td>
<input type="text" class="form-controll" value="#item.Count" />
</td>
</tr>
}
</tbody>
</table>
<input type="text" class="form-control" value="#Model.TotalPrice" />
I want to multiple count and price of each row and put it in another input using javascript. and when the user change the value of input, that input that holds the value could change automatically.
if anyone can help me i would be appreciated.
If you are using jquery then it can be achieve as below.
You can update your total on every key press in price or count input.
Add some class to your input. In my example I've took class as price, and class total for display sum.
Add keyup event as below. Also trigger it on $(document).ready to initially set the total value.
$('.price').on('keyup', function() {
var val = +$(this).val();
var valSibling = +$(this).parent().siblings('td').find('.price').val();
if (isNaN(val) || isNaN(valSibling))
return;
$(this).parent().siblings('td').find('.total').val(val * valSibling);
var finaltotal = 0;
$('.total').each(function() {
if(!isNaN($(this).val()))
finaltotal += Number($(this).val());
});
$('.finaltotal').val(finaltotal);
});
$(document).ready(function(){
$('.price').trigger('keyup');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Name</th>
<th>Category</th>
<th>Price</th>
<th>Count</th>
</tr>
</thead>
<tbody>
<tr>
<td>Name1</td>
<td>Category1</td>
<td><input type="text" class="price form-control" value="40" /></td>
<td><input type="text" class="price form-control" value="4" /></td>
<td><input type="text" class="total form-control" /></td>
</tr>
<tr>
<td>Name2</td>
<td>Category2</td>
<td><input type="text" class="price form-control" value="20" /></td>
<td><input type="text" class="price form-control" value="2" /></td>
<td><input type="text" class="total form-control" /></td>
</tr>
</tbody>
</table>
<input type="text" class="finaltotal form-control" />
var inputs = $('#container input');
inputs.keyup(function() {
var arr = inputs.toArray();
var sum = 0;
for (var i = 0; i < arr.length / 2; i++)
sum += arr[i * 2].value * arr[i * 2 + 1].value;
$('#result').val(sum);
})
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th>Count</th>
<th>Price</th>
<tr>
</thead>
<tbody id='container'>
<tr>
<td><input type='number' value='1' /></td>
<td><input type='number' value='2' /></td>
</tr>
<tr>
<td><input type='number' value='10' /></td>
<td><input type='number' value='20' /></td>
</tr>
</tbody>
</table>
Total: <input type='number' readonly id='result' readonly value='202' />
I want to multiple count and price of each row and put it in another input using javascript.
You can add another td in each tr. Then loop through all the tbody tr to calculate the value:
var tr = document.querySelectorAll('tbody tr');
function calculate(){
tr.forEach(function(el){
var td = el.querySelectorAll('td');
// If there is invalid number in input then no change in total.
if (isNaN(td[2].querySelector('input').value) || isNaN(td[3].querySelector('input').value))
return;
td[4].querySelector('input').value = td[2].querySelector('input').value * td[3].querySelector('input').value;
});
}
calculate();
.form-control{
width: 50px;
}
<table>
<thead>
<tr>
<th>Name</th>
<th>Category</th>
<th>Price</th>
<th>Count</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>Name1</td>
<td>Category1</td>
<td><input type="text" oninput="calculate()" class="form-control" value="40" /></td>
<td><input type="text" oninput="calculate()" class="form-control" value="4" /></td>
<td><input type="text" class="form-control" /></td>
</tr>
<tr>
<td>Name2</td>
<td>Category2</td>
<td><input type="text" oninput="calculate()" class="form-control" value="20" /></td>
<td><input type="text" oninput="calculate()" class="form-control" value="2" /></td>
<td><input type="text" class="form-control" /></td>
</tr>
<tr>
<td>Name3</td>
<td>Category3</td>
<td><input type="text" oninput="calculate()" class="form-control" value="30" /></td>
<td><input type="text" oninput="calculate()" class="form-control" value="3" /></td>
<td><input type="text" class="form-control" /></td>
</tr>
</tbody>
</table>

Traverse inside table rows

I have a table with multiple table rows inside it, each td has an input inside it, i'm trying to traverse inside the table row so i can set the value of an input through another input, it only works for the first table row, how can i make for all the rows in the table? and i have a button that appends a tr when i apped a new tr it doesn't set the value inside it, here is my code:
$('.myFirstInput').closest('tr').find('.mySecondInput').val('1000');
$('button').click(function () {
var tr = '<tr><td><input type="text" class="myFirstInput"</td>'+
'<td><input type="text"></td>' +
'<td><input type="text" class="mySecondInput"></td></tr>';
$('tbody').append(tr);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<th>1</th>
<th>2</th>
<th>3</th>
</thead>
<tbody>
<tr>
<td><input type="text" class="myFirstInput"></td>
<td><input type="text"></td>
<td><input type="text" class="mySecondInput"></td>
</tr>
<tr>
<td><input type="text" class="myFirstInput"></td>
<td><input type="text"></td>
<td><input type="text" class="mySecondInput"></td>
</tr>
<tr>
<td><input type="text" class="myFirstInput"></td>
<td><input type="text"></td>
<td><input type="text" class="mySecondInput"></td>
</tr>
</tbody>
</table>
<button>Append row</button>
The problem is that you are using id's. By definition, id's should be unique. When your code runs, it only applies to the first item with that id that it finds. Simply changing your id's to class should do the trick (for that part).
Secondly, it looks like you are creating rows dynamically (adding tr's). run that same function whenever you insert new rows:
$('.myFirstInput').closest('tr').find('.mySecondInput').val('1000');
$('button').click(function () {
var tr = '<tr><td><input type="text" class="myFirstInput"</td>'+
'<td><input type="text"></td>' +
'<td><input type="text" class="mySecondInput"></td></tr>';
$('tbody').append(tr);
$('.myFirstInput').closest('tr').find('.mySecondInput').val('1000');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<th>1</th>
<th>2</th>
<th>3</th>
</thead>
<tbody>
<tr>
<td><input type="text" class="myFirstInput"></td>
<td><input type="text"></td>
<td><input type="text" class="mySecondInput"></td>
</tr>
<tr>
<td><input type="text" class="myFirstInput"></td>
<td><input type="text"></td>
<td><input type="text" class="mySecondInput"></td>
</tr>
<tr>
<td><input type="text" class="myFirstInput"></td>
<td><input type="text"></td>
<td><input type="text" class="mySecondInput"></td>
</tr>
</tbody>
</table>
<button>Append row</button>
Your issue is that you're using IDs, which must be unique in HTML. Change them to classes instead and this should work as expected.
function addVal() {
var elems = $('.myFirstInput').closest('tr').find('.mySecondInput');
$.each(elems, function(s, e) {
if($(e).val() === '') {
$(e).val('1000');
}
});
}
$(document).ready(function() {
$('button').click(function () {
var tr = '<tr><td><input type="text" class="myFirstInput"</td>'+
'<td><input type="text"></td>' +
'<td><input type="text" class="mySecondInput"></td></tr>';
$('tbody').append(tr);
addVal();
});
addVal();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<th>1</th>
<th>2</th>
<th>3</th>
</thead>
<tbody>
<tr>
<td><input type="text" class="myFirstInput"></td>
<td><input type="text"></td>
<td><input type="text" class="mySecondInput"></td>
</tr>
<tr>
<td><input type="text" class="myFirstInput"></td>
<td><input type="text"></td>
<td><input type="text" class="mySecondInput"></td>
</tr>
<tr>
<td><input type="text" class="myFirstInput"></td>
<td><input type="text"></td>
<td><input type="text" class="mySecondInput"></td>
</tr>
</tbody>
</table>
<button>Append row</button>
It is not right to use multiple id with the same name in the same document. Use class instead like the following way:
$('input.mySecondInput').each(function(i, el){
$(el).val('1000');
});
$('button#btnAppendRow').click(function () {
var tr = '<tr><td><input type="text" class="myFirstInput"</td>'+
'<td><input type="text"></td>' +
'<td><input type="text" class="mySecondInput"></td></tr>';
$('tbody').append(tr);
$('input.mySecondInput:last-child').val('1000');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<th>1</th>
<th>2</th>
<th>3</th>
</thead>
<tbody>
<tr>
<td><input type="text" class="myFirstInput"></td>
<td><input type="text"></td>
<td><input type="text" class="mySecondInput"></td>
</tr>
<tr>
<td><input type="text" class="myFirstInput"></td>
<td><input type="text"></td>
<td><input type="text" class="mySecondInput"></td>
</tr>
<tr>
<td><input type="text" class="myFirstInput"></td>
<td><input type="text"></td>
<td><input type="text" class="mySecondInput"></td>
</tr>
</tbody>
</table>
<button id="btnAppendRow">Append row</button>
You must give unique identifiers for each input element. First row should have myFirstInput1 and mySecondInput1. Second row, myFirstInput2 and mySecondInput2, and so on. That way you'll be able to reference each input precisely.

javascript .innerHTML() inserts outside div

I have a table and a button, when the button is pressed it adds a new input into the table inside a div, when I add the input manually inside the div and test it it works, but when the script adds it it goes outside the table.. why is that? how can i fix this issue?
html:
..
<script> var x=0; </script>
...
<table>
<tr>
<td>From:</td>
<td><input type="text" name="from" /></td>
</tr>
<tr>
<td>To (email):</td>
<td><input type="text" name="to0" /></td>
<td><input type='button' onclick='newMail()' value='Add recipient'/> </td>
</tr>
<div id="add">
<tr>
<td>To (email):</td> <!-- this works -->
<td><input type="text" name="to0" /></td>
</tr>
</div>
<tr>
<td align="center" colspan="2"><input type="submit" value="send"></td>
</tr>
</table>
JS:
function newMail()
{
x=x+1;
var input =
" <tr>"+
" <td>To (email):</td>"+
" <td><input type='text' name='to"+x+"' /></td>"+
" </tr>";
document.getElementById("add").innerHTML += input;
}
the function works and adds the input and everything, but it goes outside the table, whilst the one inside the div that i manually added works fine and is displayed normally.
Try this one: https://jsfiddle.net/0dh52827/
JAVASCRIPT
$( document ).ready(function() {
$("#add_recipient").click( function() {
x = x + 1;
console.log(x);
var input =
" <tr>" +
" <td>To (email):</td>" +
" <td><input type='text' name='to" + x + "' /></td>" +
" </tr>";
$("#add").prepend(input);
});
});
HTML:
<script>
var x = 0;
</script>
<table id="add">
<tr>
<td>From:</td>
<td>
<input type="text" name="from" />
</td>
</tr>
<tr>
<td>To (email):</td>
<td>
<input type="text" name="to0" />
</td>
</tr>
<tr>
<td>To (email):</td>
<!-- this works -->
<td>
<input type="text" name="to0" />
</td>
</tr>
<tr>
<td align="left">
<input type="submit" value="send">
</td>
<td align="right">
<input id="add_recipient" type='button' value='Add recipient' />
</td>
</tr>
JQUERY Prepend is designed for things like this.
Check this please
function newMail() {
x = x + 1;
var input =
" <tr>" +
" <td>To (email):</td>" +
" <td><input type='text' name='to" + x + "' /></td>" +
" </tr>";
document.getElementById("add").innerHTML += input;
}
<script>
var x = 0;
</script>
<table>
<tr>
<td>From:</td>
<td>
<input type="text" name="from" />
</td>
</tr>
<tr>
<td>To (email):</td>
<td>
<input type="text" name="to0" />
</td>
</tr>
<tr>
<td>To (email):</td>
<!-- this works -->
<td>
<input type="text" name="to0" />
</td>
</tr>
<tbody id="add"></tbody>
<tr>
<td align="left">
<input type="submit" value="send">
</td>
<td align="right">
<input type='button' onclick='newMail()' value='Add recipient' />
</td>
</tr>
The element with id="add" is a <div> in a <table> (which is not properly placed but might work in some browsers). Adding code to it has at least an undefined behavior.
You should instead remove the <div> tag and give the <tr> tag the id="add" attribute and then use document.getElementById("add").appendChild() method to add a new html node. To create this node, don't use text but document.createElement() like described in MDN

Categories