Add new row (html form) after click 'Add row' button - javascript

Hi , I would to ask how to add new row after we click on the 'Add row' button. I found some Javascript code and try to edit it but it doesn't work. Thank you in advance :) Here is the code that I have been using. Would you guys tell what to do or share with me any sources regarding this matter since I haven't found one. There are some similar questions in Stackoverflow but there's no answers there.
The html code :
<h1 class="h3 mb-4 text-gray-800">Requirement Validation Principles</h1>
<div class="jumbotron jumbotron-fluid">
<div class="container">
<form>
<div class="form-row">
<div class="form-group col-md-7">
<label for="inputName1"></label>
<input type="Name" class="form-control" id="inputName1" placeholder="Name">
</div>
<div class="form-group col">
<label for="inputPassword1"></label>
<input type="name" class="form-control" id="inputPassword1" placeholder="Position">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-7">
<label for="inputName2"></label>
<input type="Name" class="form-control" id="inputName2" placeholder="Name">
</div>
<div class="form-group col">
<label for="inputPassword2"></label>
<input type="name" class="form-control" id="inputPassword2" placeholder="Position">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-7">
<label for="inputName3"></label>
<input type="Name" class="form-control" id="inputName3" placeholder="Name">
</div>
<div class="form-group col">
<label for="inputPassword3"></label>
<input type="name" class="form-control" id="inputPassword3" placeholder="Position">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-7">
<label for="inputName4"></label>
<input type="Name" class="form-control" id="inputName4" placeholder="Name">
</div>
<div class="form-group col">
<label for="inputPassword4"></label>
<input type="name" class="form-control" id="inputPassword4" placeholder="Position">
</div>
</div>
</div>
<button id="btn">Add row</button>
The javascript code :
var count=1;
$("#btn").click(function(){
$("#container").append(addNewRow(count));
count++;
});
function addNewRow(count){
var newrow='<div class="row">'+
'<div class="col-md-4">'+
'<div class="form-group label-floating">'+
'<label class="control-label">Name '+count+'</label>'+
'<input type="text" class="form-control" v-model="act" >'+
'</div>'+
'</div>'+
'<div class="col-md-4">'+
'<div class="form-group label-floating">'+
'<label class="control-label">Position '+count+'</label>'+
'<input type="text" class="form-control" v-model="section">'+
'</div>'+
'</div>'+
'</div>';
return newrow;
}

Here is the code that perfectly working.
<div class="jumbotron jumbotron-fluid" id="dataAdd">
<div class="container">
<div class="form-row">
<div class="form-group col-md-7">
<label for="inputName1"></label>
<input type="Name" class="form-control" id="inputName1" placeholder="Name" v-model="name">
</div>
<div class="form-group col">
<label for="inputPassword4"></label>
<input type="name" class="form-control" id="inputPassword1" placeholder="Position" v-model="position">
</div>
</div>
</div>
<button id="btn">Add row</button>
HTML Code input start with one.
$("#btn").click(function(){
var len=$('#dataAdd .container .form-row').length+1;
//if(len>1)
$("#dataAdd .container:last").append(' <div class="form-row">'+
'<div class="form-group col-md-7">'+
' <label for="inputName'+len+'"></label>'+
' <input type="Name" class="form-control" id="inputName'+len+'" placeholder="Name" v-model="name">'+
' </div>'+
' <div class="form-group col">'+
' <label for="inputPassword4"></label>'+
' <input type="name" class="form-control" id="inputPassword'+len+'" placeholder="Position" v-model="position">'+
' </div>'+
'</div>');
});
});
JavaScript Code added HTML in last form-control.
I have Created a working Example you can check here

Turns out there's a Javascript method called insertRow().
You'd just need to get a handle on your form by giving it and ID and then accessing that in Javascript:
var table = document.getElementById("[the ID I gave my form");
after that, use the insertRow() method on that table variable and give it a position. Then add cells to the row you just created using insertCell():
var row = table.insertRow(0);
var cell1 = row.insertCell(0);

Instead of using InsertRow() you can alternatively put the button outside your container (the div containing the "container" class) and then use javascript to create your elements.
After all elements are created, you can simply append them to follow your desired structure.
const button = document.getElementById(#btn);
button.addEventListener('click', addRow);
function addRow(event) {
const container = document.querySelector('.container');
const row = document.createElement('div');
row.classList.add('form-row');
const group = document.createElement('div');
group.classList.add('form-group');
group.classList.add('col-md-7'); // Adjust after need.
const label = document.createElement('label');
label.setAttribute('for', 'myNewInputName');
const input = document.createElement('input');
input.setAttribute('type', 'text');
input.classList.add('form-control');
input.setAttribute('placeholder', 'My new placeholder');
// Assemble our structure.
group.appendChild(label);
group.appendChild(input);
row.appendChild(group);
container.appendChild(row);
}
Here you got a working sandbox of this example: https://codesandbox.io/s/busy-lovelace-9jw2b?file=/src/index.js.
Useful links:
appendChild
createElement
querySeleector

the more simple is to use a DOMParser
const DomParser = new DOMParser()
, myForm = document.getElementById('my-form')
, bt_Add = document.getElementById('btn-add')
;
function newRow(numRow)
{
let row_N = `
<div class="form-row">
<div class="form-group col-md-7">
<label for="inputName${numRow}"></label>
<input type="Name" class="form-control" id="inputName${numRow}" placeholder="Name ${numRow}">
</div>
<div class="form-group col">
<label for="inputPassword${numRow}"></label>
<input type="name" class="form-control" id="inputPassword${numRow}" placeholder="Position ${numRow}">
</div>
</div>`
return (DomParser.parseFromString(row_N, 'text/html')).body.firstChild
}
bt_Add.onclick =()=>
{
let rowCount = myForm.querySelectorAll('div.form-row').length
myForm.appendChild(newRow(++rowCount))
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
<h1 class="h3 mb-4 text-gray-800">Requirement Validation Principles</h1>
<div class="jumbotron jumbotron-fluid">
<div class="container">
<form action="xx" id="my-form">
<div class="form-row">
<div class="form-group col-md-7">
<label for="inputName1"></label>
<input type="Name" class="form-control" id="inputName1" placeholder="Name 1">
</div>
<div class="form-group col">
<label for="inputPassword1"></label>
<input type="name" class="form-control" id="inputPassword1" placeholder="Position 1">
</div>
</div>
</form>
</div>
<button id="btn-add">Add row</button>
<!-- /.container-fluid -->
</div>
Useful links:
appendChild
querySeleectorAll
see also : What does ${} (dollar sign and curly braces) mean in a string in Javascript?

Related

Hard coded in java script, Some suggestions to decrease this code is appreciated

I have tried using js createElement, setAttribute,appendChild for achieving things.
original div
<div class = "form-row" id="components">
<div class="form-group col-md-3 mb-0">
<label for="component">Component</label>
<input type="text" class="form-control" id="component" placeholder ="component" value="">
</div>
<div class="form-group col-md-3 mb-0">
<label for="component">Each price</label>
<input type="number" class="form-control" id="price" min=0 placeholder = "Each Price" value="">
</div>
</div>
function to append elements to parent div
function components(){
var x = document.getElementById("components");
var div1 = document.createElement("div");
div1.setAttribute("class","form-group col-md-3 mb-0")
var item = document.createElement("Input");
item.setAttribute("type","text");
item.setAttribute("id","item");
item.setAttribute("value","");
item.setAttribute("class","form-control");
item.setAttribute("placeholder","item");
var div2 = document.createElement("div");
div2.setAttribute("class","form-group col-md-3 mb-0")
var price = document.createElement("Input");
price.setAttribute("type","number");
price.setAttribute("id","price");
price.setAttribute("min",0);
price.setAttribute("value","");
price.setAttribute("class","form-control");
price.setAttribute("placeholder","price");
div1.appendChild(item);
div2.appendChild(price);
x.appendChild(div1);
x.appendChild(div2);
}
The above function works with onclick event and creates child divs.
Why not just set the innerHTML of the container?
function components(){
var x = document.getElementById("components");
x.innerHTML += `
<div class="form-group col-md-3 mb-0">
<label for="component">Component</label>
<input type="text" class="form-control" id="component" placeholder ="component" value="">
</div>
<div class="form-group col-md-3 mb-0">
<label for="component">Each price</label>
<input type="number" class="form-control" id="price" min=0 placeholder = "Each Price" value="">
</div>
`;
}
It's not entirely clear, but if you're intending on calling components multiple times, use insertAdjacentHTML instead, to avoid corrupting the existing elements in the container (so that inputs with values don't get reset, and so that event listeners attached to children (if any) don't get lost):
function components(){
var x = document.getElementById("components");
x.insertAdjacentHTML('beforeend', `
<div class="form-group col-md-3 mb-0">
<label for="component">Component</label>
<input type="text" class="form-control" id="component" placeholder ="component" value="">
</div>
<div class="form-group col-md-3 mb-0">
<label for="component">Each price</label>
<input type="number" class="form-control" id="price" min=0 placeholder = "Each Price" value="">
</div>
`);
}

jQuery Cloning and incrementing input, textarea, that has name, id and for

I'm still very new to jQuery, and would need help to how to increment 3 elements in this code.
name, id & for.
The name consist of products[0]category, id consist of checkbox[0], for consist of checkbox[0] which is for labels on the checkbox that id use.
I've tried searching for examples. But all them haven't found any good results that i could learn from unfortunately. So in the codes below, they're not there to increase increment as i have totally no idea what else i can do to increase increment numbering.
$(document).ready(function() {
let $append = $('#append');
// append location's data listing
$append.on('change', '.location', function(){
var value = $(this).val();
$('.location_id').val($('#locations [value="'+value+'"]').data('locationid'));
$('.loc_desc').val($('#locations [value="'+value+'"]').data('locdesc'));
});
// enable checkbox for serialnumbers
$append.on('change','.enable-serial', function(){
let $item = $(this).closest('.product-item');
let $checkbox = $item.find('.enable');
$checkbox.prop('disabled', !this.checked);
});
// ctrl for key in checkbox
$append.on('click', '.keyin-ctrl', function() {
let $container = $(this).closest('.product-item');
let $serial = $container.find('.serial');
$container.find('.display').val(function(i, v) {
return v + $serial.val() + ';\n';
});
$serial.val('').focus();
});
// ctrl for del textarea
$append.on('click', '.undo-ctrl', function() {
let $container = $(this).closest('.product-item');
$container.find('.display').val('');
});
// clone product, increment products[x]var
$('#add_product').on('click', function() {
var itemNo = $('.product-item').length + 1;
var index = $('.product-item').length;
var regex = /^(.+?)(\d+)$/i;
let $product = $append.find('.product-item.template')
.clone()
.show()
.removeClass('template')
.insertAfter('.product-item:last');;
$product.find('span').text('#' + itemNo);
$product.find(':checkbox').prop('checked', false);
$product.find('.enable').prop('disabled', true);
$product.find('input, textarea').val('');
$('#append').append($product);
});
// delete product, but remain original template intact
$('#delete_product').on('click', function(){
var itemNo = $('.product-item').length + 1;
let $product = $append.find('.product-item:last:not(".template")');
$product.remove();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<main class="shadow border">
<h4>{{ __('Product Details') }}</h4>
<hr>
<form method="post" action="">
<!-- Multiple Product addition -->
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Product Setting') }}</label><br/>
<div class="col-sm-5">
<button type="button" id="add_product" class="btn btn-dark">{{ __('Add Product') }} <i class="fas fa-plus-square"></i></button>
<button type="button" id="delete_product" class="btn btn-dark ml-3">{{ __('Delete Last Product') }} <i class="fas fa-minus-square"></i></button>
</div>
</div>
<hr>
<!-- Frist Group -->
<div class="product" id="append">
<!-- Product Details -->
<div class="product-item template">
<span>#1</span>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Category') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]category" type="text" placeholder="eg. 333" maxlength="3"required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __('Code') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]code" type="text" placeholder="eg. 22" maxlength="2" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __('Partnumber') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]partnumber" type="text" placeholder="eg. NGH92838" required>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Brand') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]brand" type="text" placeholder="eg. Rototype" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __('Quantities') }}</label>
<div class="col-sm-2">
<input class="form-control" name="products[0]qty" type="number" placeholder="eg. 1" required>
</div>
<label class="col-sm-1 col-form-label font-weight-bold">{{ __("Location") }}</label>
<div class="col-sm-2">
<input class="form-control location" type="text" name="products[0]loc_name" list="locations" value="">
<input type="hidden" class="location_id" name="products[0]location_id" value="">
<input type="hidden" class="loc_desc" name="products[0]loc_desc" value="">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __("Description") }}</label>
<div class="col-sm-8">
<input class="form-control" name="products[0]description" type="text" placeholder="eg. Spare part for CSD2002">
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label font-weight-bold">{{ __('Seial Number(s)') }}</label>
<div class="col-sm-5">
<input class="form-control enable serial" maxlength="25" placeholder="Key in Serial Number and hit button 'Key In'" disabled>
</div>
<div class="col-sm-5">
<button class="btn btn-dark enable keyin-ctrl" type="button" disabled>{{ __('Key In') }}</button>
<button class="btn btn-dark enable undo-ctrl" type="button" disabled>{{ __('Del') }}</button>
<input class="form-check-input ml-4 mt-2 pointer enable-serial" id="checkbox[0]" type="checkbox">
<label class="form-check-label ml-5 pointer" for="checkbox[0]">{{ __('tick to enable serialnumber')}}</label>
</div>
</div>
<div class="form-group row">
<label class="col-sm-2 col-form-label"></label>
<div class="col-sm-5">
<textarea class="form-control display" name="products[0]serialnumbers" rows="5" style="resize: none;" placeholder="eg. SGH8484848" readonly></textarea>
</div>
</div>
<hr>
</div>
<!-- append start -->
</div>
<div class="form-group row">
<div class="col-sm-12 ">
#csrf
<button type="submit" class="btn btn-dark float-right ml-4">Next <i class="fas fa-caret-right"></i></button>
<!--<button type="button" class="btn btn-secondary float-right" onclick="history.back()">Previous</button>-->
</div>
</div>
<datalist id="locations">
#foreach($locations as $location)
<option value="{{ $location->loc_name}}" data-locationid="{{ $location->location_id }}" data-locdesc="{{ $location->loc_desc }}"></option>
#endforeach
</datalist>
</form>
</div>
</main>
So how do I actually achieve this to add increment to the NAME, ID and FOR my clones?
From the original template of products[0]variable to products[1]variable, checkbox[0] to checkbox[1]
If you want to increment either an ID, class, etc. you can't use .clone(), like the documentation warns:
Using .clone() has the side-effect of producing elements with
duplicate id attributes, which are supposed to be unique. Where
possible, it is recommended to avoid cloning elements with this
attribute or using class attributes as identifiers instead.
You'll have to do it "manually", following a very simple example below:
$( "#addrow" ).click(function() {
var count = $("#product").children().length;
$("#product").append("<input id='field[" + count + "]' type='text'>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="product">
</div>
<input id="addrow" type="button" value="Add field">

how to give bold styles to jquery variables

<div class="col-md-5 formdiv">
<h4 class="form-title1">Private Comment Generator</h4>
<form id="form" class="private-comments-form">
<div class="row">
<div class="col-xs-6 form-group">
<label for="sel1">Vendor :</label>
<input class="form-control" type="text" style="font-weight:bold;" id="textbox3" />
</div>
<script>
$(document).ready(function() {
$("#commentscopyBtn").click(function() {
var ven =$("#textbox3").val();
var prod =$("#textbox4").val();
var text = "Thank you for " + $("#textbox3").val() + " " ;
text += $("#textbox4").val() + "\ you can call into our support line." ;
$("#output").val(text);
});
$('#btn').click(function() {
/*Clear textarea using id */
$('#output').val('');
/*Clear all input type="text" box*/
$('#form input[type="text"]').val('');
});
});
</script>
<div class="col-xs-6 form-group">
<label for="sel1">Product :</label>
<input class="form-control" type="text" style="font-weight:bold;" id="textbox4"/>
</div>
<div class="col-xs-6 form-group">
<label for="sel1"> </label>
<input class="form-control js-textareacopybtn" id="commentscopyBtn" type="button" value="Get Content" />
</div>
<div class="col-xs-12 form-group">
<label for="sel1">Copy Content :</label>
<textarea class="col-xs-12 js-copytextarea" id="output" name="textarea" ></textarea>
</div>
<div class="col-xs-12 form-group">
<input type="button" class="reset " id="btn" value="Reset" />
</div>
</div>
</form>
</div>
Here I'm appending the values from text fields to TextArea, I want to add the bold style for that variable to highlight those values, please suggest a solution.
I want to know how to add a style for the appended text.
Give <b> for the text in variable before you append

jQuery only run function for element that gets clicked

I got a small problem that i have no clue how to solve. This HTML/PHP code bellow gets different values from a database and outputs them into the different input fields.
The HTML/PHP bellow is one element, and multiple of them are made with different values from the database. Then i got a small javascript that calulates some different values from the values that are inputted. The problem is that i got lets say 5 elements, and only wants to calculate for one of them, but if i press the "btn-oppdater" button it calculates for all the different elements.
How do i make it only calculate for the element where the button is?
Script
$('.btn-oppdater').click(function(){
$(".kval_spill").each(function(){
var fieldShow = $(this).next('.kval_spill_inner');
var b_value_kval_1 = fieldShow.find('.b_value_kval_1')[0].value;
var b_odds_kval_1 = fieldShow.find('.b_odds_kval_1')[0].value;
var e_odds_kval_1 = fieldShow.find('.e_odds_kval_1')[0].value;
var gebyr_kval = '0.02'
var q_value = ((b_odds_kval_1 / (e_odds_kval_1 - gebyr_kval)) * b_value_kval_1);
var q_tap = (b_odds_kval_1 - 1) * b_value_kval_1 - (e_odds_kval_1 - 1) * q_value;
var q_value_fixed = q_value.toFixed(2);
var q_tap_fixed = q_tap.toFixed(2);
fieldShow.find('.q_value_1')[0].value = q_value_fixed;
fieldShow.find('.q_tap_1')[0].value = q_tap_fixed;
});
});
HTML/PHP
<?php while ($row = mysqli_fetch_assoc($result2)) { echo '
<form style="margin-top: 10px;" action="" method="post" class="">
<input type="hidden" class="kval_spill">
<div class="kval_spill_inner">
<input class="" type="hidden" name="id" value="'.$row['id'].'">
<div class="form-row">
<div class="form-group col-md-4">
<input type="text" class="form-control kval_kamp_1" name="kval_kamp_1" value ="'.$row['kval_kamp_1'].'" placeholder="Kamp">
</div>
<div class="form-group col-md-3">
<div class="input-group">
<input type="text"class="form-control b_value_kval_1" name="b_value_kval_1" value ="'.$row['b_value_kval_1'].'" placeholder="Spill verdi">
<div class="input-group-append">
<span class="input-group-text">Kr</span>
</div>
</div>
</div>
<div class="form-group col-md-2">
<input type="text" class="form-control b_odds_kval_1" name="b_odds_kval_1" value ="'.$row['b_odds_kval_1'].'" placeholder="Odds">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-4">
<input type="text" class="form-control kval_marked_1" name="kval_marked_1" value ="'.$row['kval_marked_1'].'" placeholder="Type marked">
</div>
<div class="form-group col-md-3">
<div class="input-group">
<input type="text"class="form-control text-info q_value_1" name="q_value_1" value ="'.$row['q_value_1'].'" placeholder="Lay verdi">
<div class="input-group-append">
<span class="input-group-text">Kr</span>
</div>
</div>
</div>
<div class="form-group col-md-2">
<input type="text" class="form-control e_odds_kval_1" name="e_odds_kval_1" value ="'.$row['e_odds_kval_1'].'" placeholder="Odds">
</div>
</div>
<div class="form-row">
<div class="form-group col-md-2">
<div class="input-group">
<div class="input-group-append">
<span class="input-group-text">Tap</span>
</div>
<input type="text" class="form-control text-danger q_tap_1" name="q_tap_1" value ="'.$row['q_tap_1'].'" placeholder
="0.00" readonly>
<div class="input-group-append">
<span class="input-group-text">Kr</span>
</div>
</div>
</div>
<div class="col-auto">
<button type="button" class="btn btn-outline-secondary btn-oppdater">Regn ut</button>
</div>
</div>
</div>
</form>
<br>
'; }?>
Replace $(".kval_spill") with $(this).closest("form").find(".kval_spill").
But it looks like there's only one kval_spill and kvall_spill_inner in each form, so there's no need to use .each(). You can get rid of the .each() loop and just use:
var fieldShow = $(this).closest("form").find('.kval_spill_inner');
And instead of
fieldShow.find('.q_value_1')[0].value = q_value_fixed;
fieldShow.find('.q_tap_1')[0].value = q_tap_fixed;
you can write:
fieldShow.find('.q_value_1').val(q_value_fixed);
fieldShow.find('.q_tap_1').val(q_tap_fixed);

Calculate the total of item quantity into item price with dynamic HTML input fields using jQuery

I would like to calculate the total of item price multiple of item quantity using jQuery. I am using dynamic HTML input fields once I enter the amount it should calculate with quantity and give the total amount. please see the code below
My HTML Code
$(document).ready(function() {
var max_fields = 10; //maximum input boxes allowed
var wrapper = $(".add_new_field"); //Fields wrapper
var add_button = $(".add_another_product"); //Add button ID
var x = 1; //initlal text box count
$(add_button).click(function(e){ //on add input button click
e.preventDefault();
if(x < max_fields){ //max input box allowed
x++; //text box increment
$(wrapper).append('<div class="add_new_field"><div class="row"><div class="col-md-4"><div class="form-group"><label class="col-form-label"> Enter Product Name</label><input type="text" class="form-control" name="pname[]" placeholder="Product Name" tabindex="1"/></div></div><div class="col-md-4"><div class="form-group"><label class="col-form-label"> No. of Pieces</label><input type="text" class="form-control" name="pcount[]" placeholder="Product Inventory" tabindex="2" /></div></div><div class="col-md-3"><div class="form-group"><label class="col-form-label"> Estimated Amount</label><input type="text" class="form-control" name="estamount[]" placeholder="Product Inventory" tabindex="2" /></div><p>Amount: <span id="Amount"></span></p></div><i class="fa fa-remove"></i></div></div>'); //add input box
}
});
$(wrapper).on("click",".remove_field", function(e){ //user click on remove text
e.preventDefault(); $(this).parent('div').remove(); x--;
})
});
$('#EstmTotal').blur(function() {
$('.add_new_field').each(function() {
$(this).find('#Amount').html($('#PCount(0)', this).val() * $('#EstmTotal(0)', this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add_new_field">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> Enter Product Name</label>
<input type="text" class="form-control" name="pname[]" id="PName" placeholder="Product Name" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> No. of Pieces</label>
<input type="text" class="form-control" name="pcount[]" id="PCount" placeholder="No.Of Items" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="col-form-label"> Estimated Amount</label>
<input type="text" class="form-control" name="estamount[]" id="EstmTotal" placeholder="Estimated Amount of Each" />
</div>
<p>Amount: <span id="Amount"></span></p>
</div>
<!--<div class="col-md-1 removebtn"><i class="fa fa-remove"></i></div>-->
</div>
</div>
<button class="add_another_product">Add another Product <i class="fa fa-plus"></i></button>
please see the image for better understanding of the question
There is always an option to discuss
Full code here please try this. it will work according to your requirement.
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
></script>
<script type="text/javascript">
function calculate(id){ console.log(id);
// $('#EstmTotal').on('blur',function(){
$(id).parents('.add_new_field').each(function() {
var count = $(this).find("#PCount").val();
var amount = $(this).find("#EstmTotal").val();
$(this).find('#Amount').html(count*amount);
});
// });
}
$(document).ready(function(){
$(".add_another_product").on('click',function(){
var html = '<div class="add_new_field">';
html += '<div class="row">';
html += '<div class="col-md-4">';
html += '<div class="form-group">';
html += '<label class="col-form-label"> Enter Product Name</label>';
html += '<input type="text" class="form-control" name="pname[]" id="PName" placeholder="Product Name"/></div></div>';
html += '<div class="col-md-4"><divclass="form-group"><label class="col-form-label"> No. of Pieces</label>';
html += '<input type="text" class="form-control" name="pcount[]" id="PCount" placeholder="No.Of Items"/>';
html += '</div></div>';
html += '<div class="col-md-3">';
html += '<div class="form-group">';
html += '<label class="col-form-label"> Estimated Amount</label><input type="text" class="form-control" name="estamount[]" id="EstmTotal" placeholder="Estimated Amount of Each" onblur="calculate(EstmTotal)" />';
html += '</div><p>Amount: <span id="Amount"></span></p></div>';
html += '</div></div>';
$(this).before(html);
})
})
</script>
</head>
<body>
<div class="add_new_field">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> Enter Product Name</label>
<input type="text" class="form-control" name="pname[]" id="PName" placeholder="Product Name"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> No. of Pieces</label>
<input type="text" class="form-control" name="pcount[]" id="PCount" placeholder="No.Of Items"/>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="col-form-label"> Estimated Amount</label>
<input type="text" class="form-control" name="estamount[]" id="EstmTotal" onblur="calculate(EstmTotal)" placeholder="Estimated Amount of Each"/>
</div>
<p>Amount: <span id="Amount"></span></p>
</div>
<!--<div class="col-md-1 removebtn"><i class="fa fa-remove"></i></div>-->
</div>
</div>
<button class="add_another_product">Add another Product <i class="fa fa-plus"></i></button>
</body>
</html>
Do not use same id for multiple elements, user class instead of id. See below code to get amount
$(function(){
$(document).on("blur", "div.row .col-md-3 input[name='estamount[]']", function(){
var $row = $(this).closest('.row'); // get parent row
var est = $(this).val(); // read estimante
var count = $row.find('input[name="pcount[]"]').val(); // read count
$row.find('span.Amount').html(est*count); // put product
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add_new_field">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> Enter Product Name</label>
<input type="text" class="form-control" name="pname[]" placeholder="Product Name"/>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> No. of Pieces</label>
<input type="text" class="form-control" name="pcount[]" placeholder="No.Of Items"/>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="col-form-label"> Estimated Amount</label>
<input type="text" class="form-control" name="estamount[]" placeholder="Estimated Amount of Each"/>
</div>
<p>Amount: <span class="Amount"></span></p>
</div>
<!--<div class="col-md-1 removebtn"><i class="fa fa-remove"></i></div>-->
</div>
</div>
<button class="add_another_product">Add another Product <i class="fa fa-plus"></i></button>
I have made following changes in your code, where in you are finding the first element inside the array. You will get the desired results
$('#EstmTotal').blur(function() {
$('.add_new_field').each(function() {
var elem = $($('#PCount')[0]).val();
var elem2 = $($('#EstmTotal')[0]).val();
$(this).find('#Amount').html(elem * elem2);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add_new_field">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> Enter Product Name</label>
<input type="text" class="form-control" name="pname[]" id="PName" placeholder="Product Name" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> No. of Pieces</label>
<input type="text" class="form-control" name="pcount[]" id="PCount" placeholder="No.Of Items" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="col-form-label"> Estimated Amount</label>
<input type="text" class="form-control" name="estamount[]" id="EstmTotal" placeholder="Estimated Amount of Each" />
</div>
<p>Amount: <span id="Amount"></span></p>
</div>
<!--<div class="col-md-1 removebtn"><i class="fa fa-remove"></i></div>-->
</div>
</div>
<button class="add_another_product">Add another Product <i class="fa fa-plus"></i></button>
$('#EstmTotal').blur(function(){
$('.add_new_field').each(function() {
$(this).find('#Amount').html($('#PCount').val()*$('#EstmTotal').val());
});
});
JsFiddle source
I changed your code a bit. Now it checks on the blur event of both elements and it checks if both have a value. If both have it sets the calculated value. If not the div will me emptied.
Also parsing the value to a floating point number. You can change this to integers if you prefer that. The typing checking to number will be same for integers. I round the number down to 2 decimals, mainly to get around floating point number precision issues.
Last, since i thought you will have the ability to create more rows dynamically I made the blur event delegated by your .add_new_field element. This assumes your
.add_new_field is a static element. If not change this to the closest static parent of your row. For this I also changed some id selectors to class selectors because id's need to be unique.
$('.add_new_field').on('blur', '.EstmTotal, .PCount', function() {
$(this).closest('.row').each(function() {
var pcCount = parseFloat($(this).find('.PCount', this).val());
var estTotal = parseFloat($(this).find('.EstmTotal', this).val());
if (typeof pcCount === 'number' && pcCount && typeof estTotal === 'number' && estTotal) {
var calculatedValue = pcCount * estTotal;
calculatedValue = Math.round(calculatedValue * 100) / 100;
$(this).find('.Amount').text(calculatedValue);
} else {
$(this).find('.Amount').text('');
}
});
});
$('.add_another_product').on('click', function(){
$('.add_new_field').append($('.row').first().clone());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="add_new_field">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> Enter Product Name</label>
<input type="text" class="form-control" name="pname[]" placeholder="Product Name" />
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="col-form-label"> No. of Pieces</label>
<input type="text" class="form-control PCount" name="pcount[]" placeholder="No.Of Items" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="col-form-label"> Estimated Amount</label>
<input type="text" class="form-control EstmTotal" name="estamount[]" placeholder="Estimated Amount of Each" />
</div>
<p>Amount: <span class="Amount"></span></p>
</div>
<!--<div class="col-md-1 removebtn"><i class="fa fa-remove"></i></div>-->
</div>
</div>
<button class="add_another_product">Add another Product <i class="fa fa-plus"></i></button>

Categories