I'm creating an HTML table from data pulled from an XML file using JQuery. This data is to be posted via HTTP POST somewhere else.
When the XML contains multiple items (i.e. songs), it creates the respective HTML but the name attribute of the input elements stays the same.
This is the JQuery code:
<script type="text/javascript">
$(document).ready(function() {
$.get('test.xml', function(d){
$('body').append('<form id="myForm" action="http://myendpoint.xyz/test" method="post" target="_blank" />');
$('#myForm').append('<div id="mySongs" />');
$('#mySongs').append('<input type="submit" value="Submit">');
$(d).find('song').each(function() {
var $song = $(this);
var title = $song.find('title').text();
var artist = $song.find('artist').text();
var price = $song.find('price').text();
var currency = $song.find('currency').text();
var html = '<div id="mySongs"> <span id="title"><input type="text" name="title" value="' + title + '" /></span>';
html += '<span id="artist"><input type="text" name="artist" value="' + artist + '" /></span>';
html += '<span id="price"><input type="text" name="price" value="' + price + '" /></span>';
html += '<span id="currency"><input type="text" name="currency" value="' + currency + '" /></span>';
html += '</div>';
$('#mySongs').append($(html));
});
});
});
</script>
The HTML code produced after pulling the XML data and running the above code looks currently this way:
<form id="myForm" action="http://myendpoint.xyz/test" method="post" target="_blank">
<input type="submit" value="Submit">
<div id="mySongs">
<span id="title">
<input type="text" name="title" value="Song Number 1"></span>
<span id="artist">
<input type="text" name="artist" value="Artist Number 1"></span>
<span id="price">
<input type="text" name="price" value="25.00"></span>
<span id="currency">
<input type="text" name="currency" value="EUR"></span>
</div>
<div id="mySongs">
<span id="title">
<input type="text" name="title" value="Song Number 2"></span>
<span id="artist">
<input type="text" name="artist" value="Artist Number 2"></span>
<span id="price">
<input type="text" name="price" value="30.00"></span>
<span id="currency">
<input type="text" name="currency" value="USD"></span>
</div>
</form>
I would like to add an increasing number to the name attribute so that when multiple items are pulled, the code shows the respective number to identify it (For example: name="title[1]").
I would like the HTML to look as shown below instead:
<form id="myForm" action="http://myendpoint.xyz/test" method="post" target="_blank">
<input type="submit" value="Submit">
<div id="mySongs">
<span id="title">
<input type="text" name="title[1]" value="Song Number 1"></span>
<span id="artist">
<input type="text" name="artist[1]" value="Artist Number 1"></span>
<span id="price">
<input type="text" name="price[1]" value="25.00"></span>
<span id="currency">
<input type="text" name="currency[1]" value="EUR"></span>
</div>
<div id="mySongs">
<span id="title">
<input type="text" name="title[2]" value="Song Number 2"></span>
<span id="artist">
<input type="text" name="artist[2]" value="Artist Number 2"></span>
<span id="price">
<input type="text" name="price[2]" value="30.00"></span>
<span id="currency">
<input type="text" name="currency[2]" value="USD"></span>
</div>
</form>
How to achieve this? Any suggestion is highly appreciated.
You can write
title[] instead title[1]
and server automaticaly set indexes.
Can use the index argument of each callback:
$(d).find('song').each(function(i) {
var html = '<div...> <span..><input name="title['+ i +']" value="' + title + '" /></span>'
});
What about this:
var idx = 0;
$(d).find('song').each(function () {
var $song = $(this);
var title = $song.find('title').text();
var artist = $song.find('artist').text();
var price = $song.find('price').text();
var currency = $song.find('currency').text();
var html = '<div id="mySongs"> <span id="title"><input type="text" name="title[' + idx + ']" value="' + title + '" /></span>';
html += '<span id="artist"><input type="text" name="artist[' + idx + ']" value="' + artist + '" /></span>';
html += '<span id="price"><input type="text" name="price[' + idx + ']" value="' + price + '" /></span>';
html += '<span id="currency"><input type="text" name="currency[' + idx + ']" value="' + currency + '" /></span>';
html += '</div>';
$('#mySongs').append($(html));
idx++;
});
Related
by click of the button the same form is added under that form but how can i get the value of the number of times it getting printed &store it in table. How can I insert the data into table if the user add more experiences from model. On the click of the button the value in the value field should increment too and how can I enter if the user add any number of experiences so how can I enter the data in the table. I am inserting this data in table in row wise fashion in table
<div class="col-md-12" id="addexperience">
<button type="button" class="btn-primary" style="float:right;" onclick="addexperience()">Add work experience</button>
<input type="hidden" name="1experience" id="1experience" value="<?php $i = 1; ?>">
<div class="form-group">
<label>If yes, fill the following table</label>
<div class="col-md-3">
<label>Status</label>
<select class="form-control" name="status">
<option value="">Select</option>
<option value="1" <?php sel($student_experience['status'], '1'); ?>>Current</option>
<option value="0" <?php sel($student_experience['status'], '0'); ?>>Past</option>
</select>
</div>
<div class="col-md-3">
<label>Designation</label>
<input type="text" class="form-control" name="designation" value="<?php echo esc_output($student_experience['designation']);?>">
</div>
<div class="col-md-3">
<label>Duration</label>
<input type="number" class="form-control" name="duration" value="<?php echo esc_output($student_experience['duration']);?>">
</div>
<div class="col-md-3">
<label>Employer</label>
<input type="text" class="form-control" name="employer" value="<?php echo esc_output($student_experience['employer']);?>">
</div>
</div>
</div>
<script>
function addexperience(){
var i = $('#1experience').val();
i++;
$('#addexperience').append('<div class="col-md-3"> <label>Status</label> <select class="form-control" name="status'+i+'">'+
'<option value="">Select</option>'+
'<option value="Current">Current</option>'+
'<option value="Past">Past</option> </select> </div>'+
'<div class="col-md-3">'+
'<label>Designation</label>'+
'<input type="text" class="form-control" name="designation'+i+'">'+
'</div>'+
'<div class="col-md-3">'+
'<label>Duration</label>'+
'<input type="text" class="form-control" name="duration'+i+'">'+
'</div>'+
'<div class="col-md-3">'+
'<label>Employer</label>'+
'<input type="text" class="form-control" name="employer'+i+'">'+
'</div>'+
'</div>');
$(function () {
$('#1experience').val(i);
});
}
</script>
If you modify the HTML slightly in both the initial page display and within the javascript function so that the newly added items are grouped within a single container(div) and the initial elements are similarly grouped and a name assigned to the immediate ancestor of the initially displayed elements ( here I chose data-id='receiver' ) then this matter of deducing the number of times the elements have been added becomes a matter of counting the child elements within the common parent - querySelectorAll being useful here though no doubt jQuery has a concise method to do this too.
With that said though if you were to use the array syntax form form element names, such as designation[] or duration[] when the form is submitted you will have access to each element as an array in PHP ( or other backend language ) which will also, as a byproduct, reveal that same number of elements. Using the array syntax means you do not need to try to keep track of this number within the client
function addexperience() {
let i=document.querySelectorAll('[data-id="receiver"] > div').length;
$('[data-id="receiver"]').append('<div><div class="col-md-3"> <label>Status</label> <select class="form-control" name="status' + i + '">' +
'<option value="">Select</option>' +
'<option value="Current">Current</option>' +
'<option value="Past">Past</option> </select> </div>' +
'<div class="col-md-3">' +
'<label>Designation</label>' +
'<input type="text" class="form-control" name="designation' + i + '">' +
'</div>' +
'<div class="col-md-3">' +
'<label>Duration</label>' +
'<input type="text" class="form-control" name="duration' + i + '">' +
'</div>' +
'<div class="col-md-3">' +
'<label>Employer</label>' +
'<input type="text" class="form-control" name="employer' + i + '">' +
'</div>' +
'</div></div>');
alert(i);
document.querySelector('input[name="duplicates"]').value=i;
fetch( location.href, {method:'post',body:'total='+i})
.then(r=>r.text())
.then(text=>{
alert(text)
})
}
[data-id='receiver']{border:1px solid red;margin:1rem;padding:1rem;}
[data-id='receiver'] > div{margin:1rem;border:1px solid black;padding:0.5rem}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-md-12" id="addexperience">
<button type="button" class="btn-primary" style="float:right;" onclick="addexperience()">Add work experience</button>
<div data-id='receiver' class="form-group">
<div>
<label>If yes, fill the following table</label>
<div class="col-md-3">
<label>Status</label>
<select class="form-control" name="status">
<option value="">Select</option>
<option value="1" <?php sel($student_experience[ 'status'], '1'); ?>>Current</option>
<option value="0" <?php sel($student_experience[ 'status'], '0'); ?>>Past</option>
</select>
</div>
<div class="col-md-3">
<label>Designation</label>
<input type="text" class="form-control" name="designation" value="<?php echo esc_output($student_experience['designation']);?>">
</div>
<div class="col-md-3">
<label>Duration</label>
<input type="number" class="form-control" name="duration" value="<?php echo esc_output($student_experience['duration']);?>">
</div>
<div class="col-md-3">
<label>Employer</label>
<input type="text" class="form-control" name="employer" value="<?php echo esc_output($student_experience['employer']);?>">
</div>
</div>
<!-- additional content inserted here within common parent -->
</div>
</div>
<input type='hidden' name='duplicates' />
I have multiple input that when you select the option, the stock and the price would come out on other input to be used for another function.
i've tried to add unique id's for the inputs added but i just cant seem to figure out how to apply the function to the added inputs.
here is the Html:
<div id="container1">
<div class="form-group row">
<div class="col-lg-3">
<select class="form-control border-teal" id="produk_nama1" name="produk_nama[]">
<option value="">Pilih Produk</option>
#foreach ($stoks as $stok)
<option data-stok="{{$stok->stok}}" data-price="{{$stok->harga}}" value="{{$stok->produk->produk}}">{{$stok->produk->produk}}</option>
#endforeach
</select>
<div class="d-block form-text">
<span id="stok1" class="badge bg-orange"></span>
</div>
</div>
<div class="col-lg-3">
<input type="text" id="harga1" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>
</div>
<div class="col-lg-3">
<input type="number" id="jumlah1" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">
</div>
<div class="col-lg-3">
<input type="text" id="subtotal1" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>
</div>
</div>
</div>
here is the javascript:
$(document).ready(function() {
var add_button = $("#add_button");
var inputs = document.getElementsByTagName('input');
var select = document.getElementById("produk_nama");
var i = 1;
$(add_button).click(function(e) {
e.preventDefault();
i++;
$("#container1")
var html = '<div class="form-group row">';
// select buah
html += '<div class="col-lg-3">';
html += '<select class="form-control border-teal" id="produk_nama'+i+'" name="produk_nama[]">';
html += '<option value="">Pilih Produk</option>';
html += '#foreach ($stoks as $stok)';
html += '<option data-stok="{{$stok->stok}}" data-price="{{$stok->harga}}" value="{{$stok->produk->produk}}">{{$stok->produk->produk}}</option>';
html += '#endforeach';
html += '</select>';
html += '<div class="d-block form-text">';
html += '<span id="stok'+i+'" class="badge bg-orange"></span>';
html += '</div></div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="harga'+i+'" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="number" id="jumlah'+i+'" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="subtotal'+i+'" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>';
html += '</div>';
html += '</div>';
$(this).before(html);
// clone entire div
// $("#container1")
// .append(
// $("#container1")
// .children(inputs)
// .first()
// .clone()
// )
});
// main input function
$('#produk_nama'+i).on('change', function(){
alert(i);
var hargaproduk = $('#produk_nama'+i+' option:selected').data('price');
var stok = $('#produk_nama'+i+' option:selected').data('stok');
$('#stok'+i).text('Stok '+stok);
$('#harga'+i).val(hargaproduk);
});
document.getElementById('jumlah'+i).addEventListener("blur", function(){
var jumlah = $('#jumlah'+i).val();
var harga = $('#harga'+i).val();
var subtotal = jumlah * harga;
$('#subtotal'+i).val(subtotal);
})
});
any help and explanation would be much appreciated, thank you
As your first select-box i.e :produk_nama is same for all divs you can use clone() method to get clone of that select instead of writing laravel code inside jquery code.
Then , you can use $(document).on("change", "select[name*=produk_nama]".. to capture all change event on select-box . Inside this you can use .closest() and .find() method to get required values from input you needed and add the value to required inputs.Same you can do for jumlah input .
Demo Code :
$(document).ready(function() {
var add_button = $("#add_button");
var i = 1;
$(add_button).click(function(e) {
e.preventDefault();
i++;
$("#container1")
//get first div > selct clone it
var slects = $('.outer:first').find("select").clone();
var html = '<div class="form-group row outer">';
html += '<div class="col-lg-3">';
html += '<select class="form-control border-teal" id="produk_nama' + i + '" name="produk_nama[]">';
html += $(slects).html(); //add that
html += '</select>';
html += '<div class="d-block form-text">';
html += '<span id="stok' + i + '" class="badge bg-orange"></span>';
html += '</div></div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="harga' + i + '" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="number" id="jumlah' + i + '" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">';
html += '</div>';
html += '<div class="col-lg-3">';
html += '<input type="text" id="subtotal' + i + '" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>';
html += '</div>';
html += '</div>';
$(this).before(html);
});
//on change of selct
$(document).on("change", "select[name*=produk_nama]", function() {
//get attrs values
var hargaproduk = $(this).find("option:selected").attr('data-price');
var stok = $(this).find("option:selected").attr('data-stok');
//add the values to required elemnt
$(this).closest(".outer").find(".d-block span").text('Stok ' + stok)
$(this).closest(".outer").find("input[name*=harga]").val(hargaproduk);
});
$(document).on("blur", "input[name*=jumlah]", function() {
var jumlah = $(this).val(); //get value
var harga = $(this).closest(".outer").find("input[name*=harga]").val();
var subtotal = jumlah * harga;
//add value to subtotal
$(this).closest(".outer").find("input[name=subtotal]").val(subtotal);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container1">
<!--just added outer class-->
<div class="form-group row outer">
<div class="col-lg-3">
<select class="form-control border-teal" id="produk_nama1" name="produk_nama[]">
<option value="">Pilih Produk</option>
<option data-stok="something" data-price="12" value="1">1</option>
<option data-stok="something" data-price="13" value="2">2</option>
<option data-stok="something" data-price="14" value="3">3</option>
</select>
<div class="d-block form-text">
<span id="stok1" class="badge bg-orange"></span>
</div>
</div>
<div class="col-lg-3">
<input type="text" id="harga1" name="harga[]" class="form-control border-teal border-1" placeholder="Harga Produk" readonly>
</div>
<div class="col-lg-3">
<input type="number" id="jumlah1" name="jumlah[]" min="1" class="form-control border-teal border-1" placeholder="Masukkan Jumlah">
</div>
<div class="col-lg-3">
<input type="text" id="subtotal1" name="subtotal" class="form-control border-teal border-1" placeholder="Subtotal" readonly>
</div>
</div>
</div>
<button id="add_button">Add more</button>
I have dynamically added rows that I need to sum.
Added columns and total will be displayed in separate fields.
I want to sum user enter data one particular column that is "DEBIT*" columns. for example user enter 1st row on debit coloumn 100rs and user click add new row and enter 100rs that amount will be calculate and show the total field..
Here is my code.
Faild Fiddle here
var ctr = 1;
var FieldCount = 1;
$('#fst_row').on('click', '.button-add', function() {
ctr++;
var cashacc_code = 'cashacc_code' + ctr;
var cashacc = 'cashacc' + ctr;
var cash_narrat = 'cash_narrat' + ctr;
var cashdeb = 'cashdeb' + ctr;
var cashcredit = 'cashcredit' + ctr;
var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + cashacc_code + ' placeholder="NNNN" /></td><td><select class="form-control" id="cashacc" ><option value="">TDS A/C Name1</option><option value="1">Joe</option><option value="2">Joe</option><option value="3">Joe</option></select></td><td><input type="text" class=' + "joe" + ' id=' + cash_narrat + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe" + ' id=' + cashdeb + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><input type="number" class=' + "joe" + ' id=' + cashcredit + ' /></td><td style="width: 4%"><img src="./img/plus.svg" class="insrt-icon button-add"><img src="./img/delete.svg" class="dlt-icon"></td></tr>';
$('#cashTable').append(newTr);
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
});
/* second row */
var ctr = 1;
var FieldCount = 1;
$('#sndRow').on('click', '.button-add', function() {
ctr++;
var rowNum = 'rowNum' + ctr;
var cashacc_nme = 'cashacc_nme' + ctr;
var acc_narrat = 'acc_narrat' + ctr;
var accdeb = 'accdeb' + ctr;
var accCredit = 'accCredit' + ctr;
var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + rowNum + ' placeholder="NNNN" /></td><td><select class="form-control" id="cashacc_nme" ><option value="">Account Name 1</option><option value="1">Plumz</option><option value="2">Plumz</option><option value="3">Plumz</option></select></td><td><input type="text" class=' + "joe" + ' id=' + acc_narrat + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe debClass" + ' id=' + accdeb + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><input type="number" class=' + "joe" + ' id=' + accCredit + ' /></td><td style="width: 4%"><img src="./img/plus.svg" class="insrt-icon button-add"><img src="./img/delete.svg" class="dlt-icon"></td></tr>';
$('#cashTable').append(newTr);
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="cashTable" class="table table-bordered table-striped" required>
<thead>
<tr>
<th>A/c Code</th>
<th>Account Name*</th>
<th>Narration*</th>
<th>Debit*</th>
<th>Credit</th>
</tr>
</thead>
<tbody>
<tr id="fst_row">
<td>
<input type="number" id="cashacc_code" placeholder="NNNN" class="form-control" name="cashacc_code" />
</td>
<td>
<select class="form-control selectsch_items" name="cashacc" id="cashacc">
<option value="Choose and items">Choose and items</option>
<option value="1">TDS A/c Name 1</option>
<option value="2">TDS A/c Name 2</option>
</select>
</td>
<td>
<input type="text" id="cash_narrat" placeholder="Enter here" class="form-control" pattern="[a-zA-Z0-9-_.]{1,20}" name="cash_narrat" data-toggle="modal" data-target="#narratModal" />
</td>
<td>
<input type="number" id="cashdeb" placeholder="Debit Amount" class="form-control" name="cashdeb" readonly />
</td>
<td>
<input type="text" id="cashcredit" class="form-control" name="cashcredit" readonly />
</td>
<td class="tblBtn" style="width: 4%">
<img src="./img/plus.svg" class="insrt-icon button-add">
<img src="./img/delete.svg" class="dlt-icon dlt-icon">
</td>
</tr>
<tr id="sndRow">
<td>
<input type="number" class="form-control" id="rowNum" name="cashaccCode" placeholder="NNNN" />
</td>
<td>
<select class="form-control selectsch_items" name="cashacc_nme" id="cashacc_nme">
<option value="#">Choose and items</option>
<option value="1">Joe</option>
<option value="2">Joe2</option>
</select>
</td>
<td>
<input type="text" class="form-control" id="acc_narrat" placeholder="Enter here" name="acc_narrat" data-toggle="modal" data-target="#accnarratModal" />
</td>
<td>
<input type="number" class="form-control debClass" id="accdeb" placeholder="NNNNNN" name="accdeb" />
</td>
<td>
<input type="number" id="accCredit" class="form-control" name="accCredit" readonly />
</td>
<td style="width: 4%">
<img src="./img/plus.svg" id="debsum" class="insrt-icon button-add">
<img src="./img/delete.svg" class="dlt-icon">
</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-6">
<div class="cashTotal">
<p class="tableTotal">Total:</p>
</div>
</div>
<div class="col-6">
<input type="number" class="totaldeb" id="totaldbt" name="totaldbt" readonly>
</div>
</div>
I am just beginner, any help would be grateful.
Thank you.
EDIT: I'm sorry Joe, it looks like I attached your fiddle to the link other than my updated copy. Please check the link out again.
I've created a JSfiddle using yours for a working example.
I modified your code to make it easier by adding an attribute on your debit input of data-action="sumDebit" and added in this snippet.
$('body').on('change', '[data-action="sumDebit"]', function() { //Attach an event to body that binds to all tags that has the [data-action="sumDebit"] attribute. This will make sure all over dynamically added rows will have the trigger without us having to readd after ever new row.
var total = 0;
$('[data-action="sumDebit"]').each(function(i,e) { //Get all tags with [data-action="sumDebit"]
var val = parseFloat(e.value); //Get int value from string
if(!isNaN(val)) //Make sure input was parsable. If not, result come back as NaN
total += val;
});
$('#totaldbt').val(total); //Update value to total
});
I have fixed your code. please check it.
var ctr = 1;
var FieldCount = 1;
$('#fst_row').on('click', '.button-add', function() {
ctr++;
var cashacc_code = 'cashacc_code' + ctr;
var cashacc = 'cashacc' + ctr;
var cash_narrat = 'cash_narrat' + ctr;
var cashdeb = 'cashdeb' + ctr;
var cashcredit = 'cashcredit' + ctr;
var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + cashacc_code + ' name="cashaccCode" onchange="calSum()" keyup="calSum()" placeholder="NNNN" /></td><td><select class="form-control" id="cashacc" ><option value="">TDS A/C Name1</option><option value="1">Joe</option><option value="2">Joe</option><option value="3">Joe</option></select></td><td><input type="text" class=' + "joe" + ' id=' + cash_narrat + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe" + ' id=' + cashdeb + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><input type="number" class=' + "joe" + ' id=' + cashcredit + ' /></td><td style="width: 4%"><img src="./img/plus.svg" class="insrt-icon button-add"><img src="./img/delete.svg" class="dlt-icon"></td></tr>';
$('#cashTable').append(newTr);
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
});
/* second row */
var ctr = 1;
var FieldCount = 1;
$('#sndRow').on('click', '.button-add', function() {
ctr++;
var rowNum = 'rowNum' + ctr;
var cashacc_nme = 'cashacc_nme' + ctr;
var acc_narrat = 'acc_narrat' + ctr;
var accdeb = 'accdeb' + ctr;
var accCredit = 'accCredit' + ctr;
var newTr = '<tr class="jsrow"><td><input type="number" class=' + "joe" + ' id=' + rowNum + ' name="cashaccCode" onchange="calSum()" keyup="calSum()" placeholder="NNNN" /></td><td><select class="form-control" id="cashacc_nme" ><option value="">Account Name 1</option><option value="1">Plumz</option><option value="2">Plumz</option><option value="3">Plumz</option></select></td><td><input type="text" class=' + "joe" + ' id=' + acc_narrat + ' placeholder="Enter Here" /></td><td><input type="number" class=' + "joe debClass" + ' id=' + accdeb + ' ' + FieldCount + ' placeholder="NNNN" /></td><td><input type="number" class=' + "joe" + ' id=' + accCredit + ' /></td><td style="width: 4%"><img src="./img/plus.svg" class="insrt-icon button-add"><img src="./img/delete.svg" class="dlt-icon"></td></tr>';
$('#cashTable').append(newTr);
$(document).on('click', '.dlt-icon', function() {
$(this).parents('tr.jsrow').first().remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="cashTable" class="table table-bordered table-striped" required>
<tbody>
<tr id="fst_row">
///First row
<td>
<input type="number" onchange="calSum()" keyup="calSum()" id="cashacc_code" placeholder="NNNN" class="form-control" name="cashaccCode" />
</td>
<td>
<select class="form-control selectsch_items" name="cashacc" id="cashacc">
<option value="Choose and items">Choose and items</option>
<option value="1">TDS A/c Name 1</option>
<option value="2">TDS A/c Name 2</option>
</select>
</td>
<td>
<input type="text" id="cash_narrat" placeholder="Enter here" class="form-control" pattern="[a-zA-Z0-9-_.]{1,20}" name="cash_narrat" data-toggle="modal" data-target="#narratModal" />
</td>
<td>
<input type="number" id="cashdeb" placeholder="Debit Amount" class="form-control" name="cashdeb" readonly />
</td>
<td>
<input type="text" id="cashcredit" class="form-control" name="cashcredit" readonly />
</td>
<td class="tblBtn" style="width: 4%">
<img src="./img/plus.svg" class="insrt-icon button-add">
<img src="./img/delete.svg" class="dlt-icon dlt-icon">
</td>
</tr>
//// second row
<tr id="sndRow">
<td>
<input type="number" onchange="calSum()" keyup="calSum()" class="form-control" id="rowNum" name="cashaccCode" placeholder="NNNN" />
</td>
<td>
<select class="form-control selectsch_items" name="cashacc_nme" id="cashacc_nme">
<option value="#">Choose and items</option>
<option value="1">Joe</option>
<option value="2">Joe2</option>
</select>
</td>
<td>
<input type="text" class="form-control" id="acc_narrat" placeholder="Enter here" name="acc_narrat" data-toggle="modal" data-target="#accnarratModal" />
</td>
<td>
<input type="number" class="form-control debClass" id="accdeb" placeholder="NNNNNN" name="accdeb" />
</td>
<td>
<input type="number" id="accCredit" class="form-control" name="accCredit" readonly />
</td>
<td style="width: 4%">
<img src="./img/plus.svg" id="debsum" class="insrt-icon button-add">
<img src="./img/delete.svg" class="dlt-icon">
</td>
</tr>
</tbody>
</table>
<div class="row">
<div class="col-6">
<div class="cashTotal">
<p class="tableTotal">Total:</p>
</div>
</div>
<div class="col-6">
<input type="number" class="totaldeb" id="totaldbt" name="totaldbt" readonly>
</div>
</div>
<script>
function calSum(){
var calvalue = 0;
$("input[name*='cashaccCode']").each( function( key, item ) {
//alert( key + ": " + item.value );
calvalue = calvalue + parseFloat(item.value);
});
$("#totaldbt").val(calvalue);
$
}
</script>
So I am making a simple shopping cart to learn HTML / JQUERY. You add the item name, id, price, etc. and it adds it into a shopping cart. I have a couple functions that create objects from the input fields and then appends it to a table. I noticed that if I have a decimal value as the item cost, it won't append the new row to the table. If it is an integer value it works fine.
HTML:
<form role="form" id="shoppingcart">
<br style="clear:both">
<h3 style="margin-bottom: 25px; text-align: center;">Purchase Item</h3>
<!-- Div for date -->
<div class="form-group">
<input type="date" class="form-control" id="date" name="date" placeholder="Date" required>
</div>
<!-- Div for Item ID -->
<div class="form-group">
<input type="number" class="form-control" id="itemID" name="itemID" placeholder="Item ID" required>
</div>
<!-- Div for name -->
<div class="form-group">
<input type="text" class="form-control" id="name" name="name" placeholder="Name" required>
</div>
<!-- Div for description -->
<div class="form-group">
<textarea class="form-control" type="textarea" id="description" name="description" placeholder="description" maxlength="25" rows="7"></textarea>
</div>
<!-- Div for quantity -->
<div class="form-group">
<input type="number" class="form-control" id="quantity" name="quantity" placeholder="Quantity" required>
</div>
<!-- Div for unit price -->
<div class="form-group">
<input type="number" class="form-control" id="unitPrice" name="unitPrice" placeholder="Unit Price" required>
</div>
<!-- div for cost -->
<div class="form-group">
<input type="number" class="form-control" id="cost" name="cost" placeholder="Cost" disabled="disabled" required>
</div>
<label><span> </span><input class="addrow" type="submit" value="Add to Cart" /></label>
</form>
</div>
</div>
JS:
$(document).ready(function () {
var mainElement = document.getElementById('shoppingCart');
//Serialization form to create object from inputs
function serializeForm() {
var inputFields = $(mainElement).find('form :input');
var result = {};
$.each(inputFields, function (index, value) {
if ($(value).attr('name')) {
result[$(value).attr('name')] = $(value).val();
}
});
return result;
}
$(mainElement).find('input[type="submit"]').click(function (evt) {
evt.preventDefault();
if ($(evt.target).parents('form')[0].checkValidity()) {
var shoppingItem = serializeForm();
var html = '<tr><td>' + shoppingItem.itemID + '</td>' +
'<td>' + shoppingItem.name + '</td>' +
'<td>' + shoppingItem.description + '</td>' +
'<td>' + shoppingItem.quantity + '</td>' +
'<td>' + shoppingItem.unitPrice + '</td>' +
'<td class="cost">' + shoppingItem.cost + '</td></tr>'
$('table tbody').append(html);
$(mainElement).find('input[type="text"]').val('');
//$(calculateSum);
}
});
});
the calculateSum call is to another function that calculates shipping, total, tax costs and updates other input fields with them
Turns out on checkValidation() input type of "number" returns as false if there is a decimal, including step="any" in the tag allowed decimal places to be used in that input and validate.
You need to modify your div for cost to:
<div class="form-group">
<input type="number" class="form-control" id="cost"
name="cost" placeholder="Cost" step="any" required>
</div>
Notice step="any" attribute value.
When you don't provide any value the value is incremented by 1. Even in any the value would get incremented by 1 but if you mention 3.2, it would increment to 4.2 etc.
Additional benefit is that this if condition would pass:
if ($(evt.target).parents('form')[0].checkValidity())
Looks like this is what you are looking for?
I have a problem in my form. In my form the user can add multiple discount codes. And what I need to validate are the two textboxes these are 'date start' and 'date expired' and I need to find out if these are empty. Before allowing the user to add another row again.
Here's my code:
function addProductDiscountCode() {
var html = '<tr id="row-count-' + iterator + '">';
html += ' <td>';
html += ' <input type="text" name="discount_code[' + iterator + '][code]" class="form-control" readonly="readonly" value="' + code + '" />';
html += ' </td>';
html += ' <td class="text-center">';
html += ' <input type="text" name="discount_code[' + iterator + '][percentage]" class="form-control text-center" />';
html += ' </td>';
html += ' <td class="text-center">';
html += ' <div class="input-group date"><input name="discount_code[' + iterator + '][date_start]" value="" id="start-date-' + iterator + '" placeholder="YYYY-MM-DD" data-date-format="YYYY-MM-DD" class="form-control date_set" type="text" readonly><span class="input-group-btn"><button type="button" class="btn btn-default"><i class="fa fa-calendar"></i></button></span></div>';
html += ' </td>';
html += ' <td class="text-center">';
html += ' <div class="input-group date"><input name="discount_code[' + iterator + '][date_expired]" value="" id="end-date-' + iterator + '" placeholder="YYYY-MM-DD" data-date-format="YYYY-MM-DD" class="form-control date_end" type="text" readonly><span class="input-group-btn"><button type="button" class="btn btn-default"><i class="fa fa-calendar"></i></button></span></div>';
html += ' </td>';
html += ' <td style="width: 15%">';
html += ' <select class="form-control" name="discount_code[' + iterator + '][status ]">';
html += ' <option value="0">Disable</option>';
html += ' <option value="1">Activate</option>';
html += ' </select>';
html += ' </td>';
html += ' <td class="text-center"><button type="button" onClick="removeCode(' + iterator + ');" class="btn btn-danger"><i class="fa fa-minus-circle"></i></button></td>';
html += '</tr>';
$("#product-discount-code tbody").append(html);
iterator++;
$('.date').datetimepicker({
pickTime: false
});
}
And this will result in a row like this:
<tr id="row-count-1">
<td>
<input name="discount_code[1][code]" class="form-control" readonly="readonly" value="4npi7YIIrv" type="text">
</td>
<td class="text-center">
<input name="discount_code[1][percentage]" class="form-control text-center" type="text">
</td>
<td class="text-center">
<div class="input-group date">
<input name="discount_code[1][date_start]" value="" id="start-date-1" placeholder="YYYY-MM-DD" data-date-format="YYYY-MM-DD" class="form-control date_set" readonly="" type="text">
<span class="input-group-btn">
<button type="button" class="btn btn-default"><i class="fa fa-calendar"></i></button>
</span>
</div>
</td>
<td class="text-center">
<div class="input-group date">
<input name="discount_code[1][date_expired]" value="" id="end-date-1" placeholder="YYYY-MM-DD" data-date-format="YYYY-MM-DD" class="form-control date_end" readonly="" type="text">
<span class="input-group-btn">
<button type="button" class="btn btn-default"><i class="fa fa-calendar"></i></button>
</span>
</div>
</td>
<td style="width: 15%">
<select class="form-control" name="discount_code[1][status ]">
<option value="0">Disable</option>
<option value="1">Activate</option>
</select>
</td>
<td class="text-center">
<button type="button" onclick="removeCode(1);" class="btn btn-danger">
<i class="fa fa-minus-circle"></i>
</button>
</td>
</tr>
I added a console print in the add action:
$(".date_start").val();
$(".date_end").val();
And It only get the value of the first row. I need
The getter method like .val(), in jQuery will return the value of the first element in the set not of all the elements(with exceptions like .text())
You can use a loop based logic to see whether all the elements has values
var date_set = true;
$('.date_set').each(function () {
if ($(this).val().length == 0) {
date_set = false;
return false;
}
})