$(document).ready(function(){
var srno=1;
var srnoarray= new Array();
$(".addRow").click(function(){
var ToAppend='<tr><td><input type="text" class="form-control" style="width:40px;" name="srno_[]" id="id_srno_'+srno+'" value="'+srno+'" readonly="readonly" /></td>';
ToAppend+='<td>';
ToAppend+='<select class="form-control" name="product_name_'+srno+'" id="product_name_'+srno+'" onchange="return onSelectChangeajax(this.value,'+srno+')">';
ToAppend+='<option value="0">Select Product</option>';
ToAppend+='</select>';
ToAppend+='</td>';
ToAppend+='<td><input type="text" class="form-control" name="product_prise_'+srno+'" id="product_prise_'+srno+'" placeholder="Purchase Prise" onblur="calAmount('+srno+')" /></td><td><input type="text" class="form-control" name="product_qty_'+srno+'" id="product_qty_'+srno+'" value="1" placeholder="Quantity" onblur="calAmount('+srno+')"/></td><td><input type="text" class="form-control" name="product_amt_'+srno+'" id="product_amt_'+srno+'" placeholder="Amount" onblur="calAmount('+srno+')"/></td><td><img src="dist/img/removerow.png" onclick="deleteRow(this),deleteArrayVal.apply(this,'+srnoarray+');" /></td></tr>';
srnoarray.push(srno);
$("#purchaseItems").append(ToAppend);
console.log(srnoarray);
srno++;
});
});
function deleteRow(rwo)
{
var i=rwo.parentNode.parentNode.rowIndex;
document.getElementById("purchaseItems").deleteRow(i);
}
function deleteArrayVal(val)
{
console.log(val);
}
Above functions add the dynamic row and remove the row in table. I have created an array called srnoarray and I have added srno in that array on every tr get added dynamically. deleteRow is the function to remove tr, but when i remove tr i want to remove particular srno from srnoarray.
<img src="dist/img/removerow.png" onclick="deleteRow(this),deleteArrayVal('+srnoarray+');" />
I tried passing array as argument in the function but that is not of use.
how should I do that??
I see that you are trying to use the method here :
document.getElementById("purchaseItems").deleteRow(i);
For this, you might need to add the deleteRow as a prototype to work.
But please elaborate a little bit what exactly you want to delete from the array.
Thanks.
First of all, I would recommend to use a templating engine (e.g. handlebars)
to keep your js cleaner (no HTML in jquery). Improves readability.
I also would look at angularjs because then you will have it easier to keep your js data in synch with your DOM.
For your row remove button you could add a data attribute to each row so you can easily get the clicked row in your click handler.
Please have a look at the demo below and here at jsFiddle.
var row = $("#row-template").html(),
rowTemplate = Handlebars.compile(row),
purchasedItems = [];
/*
var context = {srno: 0};
var html = rowTemplate(context);
*/
function addRow() {
purchasedItems.push({
srno: purchasedItems.length+1,
products: [ {// just some dummy products
name:'pizza',
selected: 'selected'
},
{name:'pasta'
},
{name:'hamburger'}
]
});
console.log(purchasedItems);
refreshTable();
}
function refreshTable() {
$('#purchaseItems').empty();
$.each(purchasedItems, function(index, item) {
$('#purchaseItems').append(rowTemplate(item));
});
}
function getRowId(context) {
return $(context).parent().parent().attr('data-rowId');
}
/* not working --> needed to update the data in the array
$('#purchaseItems').on('change', '.productSelection', function() {
var index = getRowId(this);
console.log(index);
});
*/
$('#purchaseItems').on('click', '.removeRow', function() {
var index = getRowId(this);
console.log(index);
purchasedItems.pop(index);
console.log(purchasedItems);
refreshTable();
});
$('#add').click(function() {
addRow();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.3/handlebars.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="row-template" type="text/x-handlebars-template">
<tr data-rowId="{{srno}}">
<td>
<input type="text" class="form-control" style="width:40px;" name="srno_[]" id="id_srno_{{srno}}" value="{{srno}}" readonly="readonly" /></td>
<td>
<select class="form-control" name="product_name_{{srno}}" id="product_name_{{srno}}" class="productSelection">
{{#each products}}
<option value="{{this.name}}" {{this.selected}}>{{this.name}}</option>
{{/each}}
</select>
</td>
<td>
<input type="text" class="form-control" name="product_prise_{{srno}}" id="product_prise_{{srno}}" placeholder="Purchase Prise" onblur="calAmount({{srno}})" />
</td>
<td>
<input type="text" class="form-control" name="product_qty_{{srno}}" id="product_qty_{{srno}}" value="1" placeholder="Quantity" onblur="calAmount({{srno}})"/>
</td>
<td>
<input type="text" class="form-control" name="product_amt_{{srno}}" id="product_amt_{{srno}}" placeholder="Amount" onblur="calAmount({{srno}})"/>
</td>
<td>
<!--<img src="dist/img/removerow.png"--> <button class="removeRow">remove</button>
</td>
</tr>
</script>
<button id="add">add</button>
<div id="purchaseItems"></div>
function deleteArrayVal(value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
}
Related
I've been using JavaScript to create new row on the table so that each input data will save in database. please refer example below.
Script for adding row on the table
<script type="text/javascript">
$(document).ready(function(){
var html='<tr><td><input type="text" size="2" class="form-control" name="qt[]" id="qt"
oninput="calculate();" required></td>
<input type="text" size="5" class="form-control" name="uc[]" id="cf" oninput="calculate();"
placeholder="₱0.00" required></td>
<td><center><input type="text" size="5" class="form-control" name="ta[]" id="result"
required></center></td><input type="button" class="form-control" name="remove" id="remove"
value="-"></td></tr>';
var x = 1;
$("#addd").click(function(){
$("#tb_field").append(html);
});
$("#tb_field").on('click','#remove',function(){
$(this).closest('tr').remove();
x--;
});
});
</script>
Script for multiplying two input types in the first row of the table
<script>
function calculate() {
var myBox1 = document.getElementById("qt").value;
var myBox2 = document.getElementById("cf").value;
var result = document.getElementById("result");
var myResult = myBox1 * myBox2;
var format2 = myResult.toLocaleString("USD");
document.getElementById("result").value = format2;
}
</script>
I made a working JSFiddle example. The code is:
<table id="myTable">
</table>
<input type="button" name="addRow" id="addRow" value="+">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js?Version=43"></script>
<script>
function newRowHtml(rowNumber)
{
return '<tr id="row'+rowNumber+'"><td><input type="text" size="2" name="qt[]" class="qt" oninput="calculate('+rowNumber+');" value="0" required></td><td><input type="text" size="5" name="uc[]" class="cf" oninput="calculate('+rowNumber+');" value="0" required></td><td><center><input type="text" size="5" name="ta[]" class="ta" required></center></td><td><input type="button" name="remove" id="removeRow" value="-"></td></tr>';
}
var rowNumber = 1;
$("#addRow").click(function() {
$("#myTable").append(newRowHtml(rowNumber));
calculate(rowNumber);
rowNumber++;
});
$("#myTable").on('click', '#removeRow', function() {
$(this).closest('tr').remove();
});
function calculate(rowNumber)
{
let row = $("#row"+rowNumber);
let qt = parseInt(row.find(".qt").val());
let cf = parseInt(row.find(".cf").val());
row.find(".ta").val(qt * cf);
}
</script>
I have numbered the rows, which is easier than number cells, and make fully use of JQuery. I hope this makes some sense, and that you can adapt it to your needs.
You can, of course, use parseFloat() instead of parseInt(), but having values like ₱0.00 in your input could complicate things.
I can't find the average of all the inputs. My code only reads the input that i stated in html, but doesn't read the other dynamic ones.
Heres my code:
$(document).ready(function(){
// adds a new row
$(".addCF").click(function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> Add Remove</td></tr>');
});
// deletes the row
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
$("#customFields").on('click','.add',function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> Add Remove</td></tr>');
});
$("#click").click(function(){
var isbn = document.getElementById('customFieldName').value;
alert(isbn / $("input").length)
$("#averageGrade").text("Average Grade: " + isbn)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="form-table" id="customFields">
<tr valign="top">
<th scope="row"><label for="customFieldName">Custom Field</label></th>
<td>
<input type="text" class="code" id="customFieldName" name="customFieldName[]" placeholder="Input Name" />
Add
</td>
</tr>
</table>
<button id = "click" class = "btn btn-primary" >Hi</button>
<p id = "averageGrade">Average Grade:</p>
Please help!
Thanks!
Each element.id must be unique - please change customFieldName to a class, and then iterate over the inputs and calculate the average. Also, you can reuse the same class for all "add" buttons and save that string in a variable so you don't have to paste it multiple times.
let inputTemplate = '<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="text" class="customFieldName code" name="customFieldName[]" value="" placeholder="Input Name" /> Add Remove</td></tr>';
$(document).ready(function() {
// adds a new row
$("#customFields").on('click', '.addCF', function() {
$("#customFields").append(inputTemplate);
});
// deletes the row
$("#customFields").on('click', '.remCF', function() {
$(this).parent().parent().remove();
});
$("#click").click(function() {
let fields = $('.customFieldName'),
total = 0;
for (let field of fields)
total += Number(field.value);
let average = total / fields.length;
$("#averageGrade").text("Average Grade: " + average);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="form-table" id="customFields">
<tr valign="top">
<th scope="row"><label>Custom Field</label></th>
<td>
<input type="text" class="customFieldName code" name="customFieldName[]" placeholder="Input Name" />
Add
</td>
</tr>
</table>
<button id="click" class="btn btn-primary">Hi</button>
<p id="averageGrade">Average Grade:</p>
First of all, you need a way to select all the fields. Since id must (should) be unique, you could use the name or the class .code and remove id="customFieldName".
Then, getElementById, as its name suggests, returns one element. You need to select them all! If you're using class names, you can use getElementsByClassName, or querySelectorAll, or, since you're already using jQuery, just $(".code"), along with a loop to read each input's value (it you use jQuery, you can also use each()).
var sum=0,count=0,average;
$(".code").each(function() {
var value=parseInt($(this).val());
//You may want to validate the field
if(!isNaN(value)) sum+=value;
count++;
});
average=sum/count;
...
As many has pointed out (including myself in the comment section), you are going about using the wrong selector. id is a unique selector, meaning that the script will look at the first instance of the id and then stop immediately after.
What you need to do is use a selector that goes through every occurance of its instance. This is why class selectors exist. That will be the first fix in your code.
How I would go about calculating the average, personally, would be to make an array and push(); the values of the grades into the array. We will also need to do a parseInt() to make sure that our values are in fact handled as numbers. Otherwise, they'll be interpreted as strings.
You will then need to loop through the array, sum the values and divide by the length of the array.
HTML Example:
<div class="row">
<div class="col-12">
<table class="table form-table" id="customFields">
<tr valign="top">
<th scope="row"><label>Custom Field</label></th>
<td>
<input type="number" class="customFieldName" placeholder="Input Number" />
Add
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4">
<button id="calcAvrgBtn" class="btn-primary">Calculate average grade</button>
</div>
<div class="col-md-4">
<p id="averageCalc"></p>
</div>
</div>
jQuery Example:
$('.addCF').on("click", function() {
$("#customFields").append('<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="number" class="customFieldName" placeholder="Input Number" /> Remove</td></tr>');
});
$(document).on("click", "a.remCF" , function() {
$(this).parent().parent().remove();
});
$('#calcAvrgBtn').on("click", function() {
let gradeArr = [];
$('.customFieldName').each(function() {
gradeArr.push(parseInt($(this).val()));
});
let total = 0;
for(var i = 0; i < gradeArr.length; i++) {
total += gradeArr[i];
}
let avg = total / gradeArr.length;
$('#averageCalc').text("The average grade is: "+avg);
});
Codepen example can be found here.
Snippet Example:
$('.addCF').on("click", function() {
$("#customFields").append('<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="number" class="customFieldName" placeholder="Input Number" /> Remove</td></tr>');
});
$(document).on("click", "a.remCF" , function() {
$(this).parent().parent().remove();
});
$('#calcAvrgBtn').on("click", function() {
let gradeArr = [];
$('.customFieldName').each(function() {
gradeArr.push(parseInt($(this).val()));
});
let total = 0;
for(var i = 0; i < gradeArr.length; i++) {
total += gradeArr[i];
}
let avg = total / gradeArr.length;
$('#averageCalc').text("The average grade is: "+avg);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-12">
<table class="table form-table" id="customFields">
<tr valign="top">
<th scope="row"><label>Custom Field</label></th>
<td>
<input type="number" class="customFieldName" placeholder="Input Number" />
Add
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4">
<button id="calcAvrgBtn" class="btn-primary">Calculate average grade</button>
</div>
<div class="col-md-4">
<p id="averageCalc"></p>
</div>
</div>
i used this script to create a repeat form
http://demo.techstream.org/Dynamic-Form-Processing-with-PHP/
in my form i use a javascript for datepicker this code work for the first row but when not whorking in the second row and the same problem for duration difference between 2 date and for my progress bar. All this work in the first row when i add a second row the datepicker and duration and progress bar stop working but work in the first
html code:
<td>
<input id="startdate" name="startdate[]" type="date" placeholder="planing Date" onfocus="(this.type='date')" onblur="(this.type='text')" onChange="onDateChange()" onchange="cal()">
</td>
<td>
<input id="enddate" name="enddate[]" type="text" placeholder="planing Date" onfocus="(this.type='date')" onblur="(this.type='text')" onchange="cal()">
</td>
<td>
<input id="duration" name="duration[]" type="text" placeholder="Duration" onChange="onDateChange()">
</td>
<td> <td>
<input id="prb" name="txt_prb[]" type="text" placeholder="%">
<div id="bar"><span id="progresss"></span></div>
</td>
javascript code:
<script type="text/javascript">
function GetDays(){
var dropdt = new Date(document.getElementById("enddate").value);
var pickdt = new Date(document.getElementById("startdate").value);
return parseInt((dropdt - pickdt) / (24 * 3600 * 1000));
}
function cal(){
if(document.getElementById("startdate")){
document.getElementById("duration").value=GetDays();
}
}
</script>
<script>
$(document).on('click', ':not(form)[data-confirm]', function(e){
if(!confirm($(this).data('confirm'))){
e.stopImmediatePropagation();
e.preventDefault();
}
});
$(document).on('submit', 'form[data-confirm]', function(e){
if(!confirm($(this).data('confirm'))){
e.stopImmediatePropagation();
e.preventDefault();
}
});
$(document).on('input', 'select', function(e){
var msg = $(this).children('option:selected').data('confirm');
if(msg != undefined && !confirm(msg)){
$(this)[0].selectedIndex = 0;
}
});
</script>
<script>
$(document).on('click', ':not(form)[data-confirm]', function(e){
if(!confirm($(this).data('confirm'))){
e.stopImmediatePropagation();
e.preventDefault();
}
});
$(document).on('submit', 'form[data-confirm]', function(e){
if(!confirm($(this).data('confirm'))){
e.stopImmediatePropagation();
e.preventDefault();
}
});
$(document).on('input', 'select', function(e){
var msg = $(this).children('option:selected').data('confirm');
if(msg != undefined && !confirm(msg)){
$(this)[0].selectedIndex = 0;
}
});
</script>
Use classes instead of id if you are planning to duplicate the html, so:
<td>
<input class="startdate" name="startdate[]" type="date" placeholder="planing Date" onfocus="(this.type='date')" onblur="(this.type='text')" onChange="onDateChange()" onchange="cal()">
</td>
<td>
<input class="enddate" name="enddate[]" type="text" placeholder="planing Date" onfocus="(this.type='date')" onblur="(this.type='text')" onchange="cal()">
</td>
<td>
<input class="duration" name="duration[]" type="text" placeholder="Duration" onChange="onDateChange()">
</td>
<td>
<input class="prb" name="txt_prb[]" type="text" placeholder="%">
<div class="bar"><span class="progresss"></span></div>
</td>
And adapt your javascript functions using document.getElementByClassName() instead of document.getElementById()
or
pass the element reference in your function calls like onChange="cal(this)" it solves the issue in this post: Pass parameters throw onchange function
Hi I'm new for programming and I'm facing one problem.
I have 3 input for values and 1 input for total. What I need is when I change the value in any input total should change automatically.
<input type="text" name="Amt" id="amount" class="form-control" />
<input type="text" name="Amt" id="amount" class="form-control" />
<input type="text" name="Amt" id="amount" class="form-control" />
And for total I have:
<input type="text" class="form-control" name="total" id="total" value="" />
And below is the script:
<script type="text/javascript">
$('#amount').change(function() {
$('#total').attr('value', function() {
var result = 0;
$('#amount').each(function() {
result += $(this).attr('value');
});
return result;
});
});
</script>
You have multiple ids for amount. These should be changed to classes. In addition, the value for each amount will be picked out by jQuery as a string, so that needs to be changed to an integer:
$('.amount').change(function () {
var result = 0;
$('.amount').each(function () {
result += +$(this).val();
});
$('#total').val(result);
});
Fiddle.
I wanna fill a form automatically by clicking on a div which has all the contents required for the form.
My div -
<div class="ab">
<ul>
<li>Sahar Raj</li>
<li>Address.</li>
<li>City</li>
<li>State</li>
<li>Pin</li>
<li>9876543210</li>
</ul>
</div>
Form -
<input class="required" type="text" name="name" />
<textarea name="address" class="required"></textarea>
<input class="required" type="text" name="city" />
<select name="state">
<option value="0">State1</option>
<option value="1">State2</option>
</select>
<input class="required" type="text" name="pin" />
<input class="required" type="text" name="phone" />
Any idea how to achieve this? Thanks
Try this:
$(document).ready(function () {
$(".ab").on("click", function () {
$(".ab ul >li").each(function (x, value) {
var text = $(this).html();
var dom = $("input,textarea,select").get(x);
$(dom).val(text);
});
})
});
JSFIDDLE DEMO
You can use a mix of map and each methods to get it working.
Remember that the order is important to get it working. If you have haphazard order, you can use the data-* attributes to store the related field info and then populate it.
$(function () {
$('div.ab').click(function() {
var data = $('.ab li').map(function () {
return this.innerHTML;
// or return $(this).text();
}).get();
$('input').each(function (i) {
this.value = data[i];
// or $(this).val(data[i]);
});
});
});
Check Fiddle
UPDATE
I have used data-* attributes to establish a relationship between the elements as they are no more of the same kind. This will be mapped to the name attribute of the field. Also encased the fields in a container as that makes them easier to select.
HTML
<div class="ab">
<ul>
<li data-key="name">Sahar Raj</li>
<li data-key="address">Address.</li>
<li data-key="city">City</li>
<li data-key="state">State2</li>
<li data-key="pin">Pin</li>
<li data-key="phone">9876543210</li>
</ul>
</div>
<div class="container">
<input class="required" type="text" name="name" />
<textarea name="address" class="required"></textarea>
<input class="required" type="text" name="city" />
<select name="state">
<option value="0">State1</option>
<option value="1">State2</option>
</select>
<input class="required" type="text" name="pin" />
<input class="required" type="text" name="phone" />
</div>
JS
$(function () {
$('div.ab').click(function () {
$('.container').children().each(function() {
// Get the corresponding key value from li.
var $this = $(this),
key = $this.attr('name');
// Find the li with that key
var txt = $('.ab li[data-key="'+ key +'"]').text();
$this.val(txt);
});
});
});
Check Data Fiddle
I'm guessing your inputs are all in a form and that the ul is always in the right order.
If that is true you can use:
$(function(){
$('div.ab').on('click',function(){
$('form input').each(function(index){
$(this).val($('div.ab ul li:eq(' + index + ')').html());
});
});
});
You can add id for every <li> and bind the click, for example the name:
HTML:
<li id="name">Sahar Raj</li>
jQuery:
$('.ab').on('click', function(){
$('input[name="name"]').val($('#name').html());
});
var counter = 0;
$("#clickme").click(function() {
$("#list li").each(function() {
var text = $(this).text();
$("input:eq(" + counter + ")").val(text);
counter++;
});
});
http://jsfiddle.net/PgYjH/1/
You can use this
$('div ul li').click(function () {
var divIndex = $(this).index();
var divText = $(this).text();
$('input').each(function () {
if ($(this).index() == divIndex) {
$(this).prop('value', divText);
}
});
});
On the click of one <li> it will read its index position and take its value/text. Then look for the <input> with same index and give the value/text to it.
The best would be to have data- attributes on both input and li, to avoid problems if you mix up the order how they are.
DEMO HERE