create a "remove fields" button after new fields are dynamically added? - javascript

I have a simple form that adds an extra row of fields on the click of
a green button.
I would like a 2nd red button to appear to the right of the green button
after the the green button is clicked for the 1st time.
I would like this red button to remove the most recent row of fields
added every time it is clicked
i would like for the red button to disappear when all added rows
have been removed.
Can anyone help me with this? I'm not very experienced with javascript or jquery obviously.
The code is as follows:
test.php
<form role="form">
<h3>
Band Details
<small>Enter each band name and primary contact information...</small>
</h3>
<div class="well" id="newBandRows">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for "newBandName">Band Name:</label>
<input type="text" class="form-control" id="newBandName" name="newBandName" placeholder="Enter Band Name" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="primaryContact">Primary Contact:</label>
<input type="text" class="form-control" id="primaryContact" name="primaryContact" placeholder="Enter Name" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for "personEmail">Primary Email:</label>
<input type="email" class="form-control" id="primaryEmail" name="primaryEmail" placeholder="Enter Email" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for "personPhone">Primary Phone #:</label>
<input type="text" class="form-control" id="primaryPhone" name="primaryPhone" placeholder="Enter Phone #" />
</div>
</div>
</div>
</div>
<div id="newRowButton">
<div class="row">
<div class="col-md-1">
<button type="button" class="btn btn-success pull-left" onClick="addNewBandRow();">+</button>
</div>
<div class="col-md-1">
</div>
<div class="col-md-7">
</div>
<div class="col-md-3 padding-top-10">
<button type="submit" class="btn btn-primary pull-right" align="right">Submit</button>
</div>
</div>
</div>
</form>
Javascript:
var band_i = 0;
function addNewBandRow() {
band_i++;
var bandDiv = document.createElement('div');
bandDiv.innerHTML = '<div class="row"><div class = "col-md-3"><input type="text" class="form-control" id="newBandName' + band_i + '" name="newBandName' + band_i + '" placeholder="Enter Band Name"/></div><div class="col-md-3"><input type="text" class="form-control" id="primaryContact' + band_i + '" name="primaryContact' + band_i + '" placeholder="Enter Name"/></div> <div class="col-md-3"><input type="email" class="form-control" id="primaryEmail' + band_i + '" name="primaryEmail' + band_i + '" placeholder="Enter Email"/></div><div class="col-md-3"><input type="text" class="form-control" id="primaryPhone' + band_i + '" name="primaryPhone' + band_i + '" placeholder="Enter Phone #"/></div></div><br>';
document.getElementById('newBandRows').appendChild(bandDiv);
}

Tested Copy
<html>
<head>
<script>
var band_i = 0;
var click = 0;
function addNewBandRow() {
click++;
band_i++;
var bandDiv = document.createElement('div');
bandDiv.innerHTML = '<div class="row"><div class = "col-md-3"><input type="text" class="form-control" id="newBandName' + band_i + '" name="newBandName' + band_i + '" placeholder="Enter Band Name"/></div><div class="col-md-3"><input type="text" class="form-control" id="primaryContact' + band_i + '" name="primaryContact' + band_i + '" placeholder="Enter Name"/></div> <div class="col-md-3"><input type="email" class="form-control" id="primaryEmail' + band_i + '" name="primaryEmail' + band_i + '" placeholder="Enter Email"/></div><div class="col-md-3"><input type="text" class="form-control" id="primaryPhone' + band_i + '" name="primaryPhone' + band_i + '" placeholder="Enter Phone #"/></div></div><br>';
document.getElementById('newBandRows').appendChild(bandDiv);
if (click === 1) {
var rmDiv = document.createElement('div');
rmDiv.innerHTML = '<div id="remove">Remove</div>';
document.getElementById('remover').appendChild(rmDiv);
}
}
function removeNewBandRow() {
var container = document.getElementById("newBandRows")
var children = container.childNodes;
container.removeChild(children[children.length - 1]);
//console.log(children.length);
if (children.length === 3) {
var redbutton = document.getElementById("remover");
redbutton.parentNode.removeChild(redbutton);
}
}
</script>
</head>
<body>
<form role="form">
<h3>
Band Details
<small>Enter each band name and primary contact information...</small>
</h3>
<div class="well" id="newBandRows">
<div class="row">
<div class="col-md-3">
<div class="form-group">
<label for "newBandName">Band Name:</label>
<input type="text" class="form-control" id="newBandName" name="newBandName" placeholder="Enter Band Name" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="primaryContact">Primary Contact:</label>
<input type="text" class="form-control" id="primaryContact" name="primaryContact" placeholder="Enter Name" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for "personEmail">Primary Email:</label>
<input type="email" class="form-control" id="primaryEmail" name="primaryEmail" placeholder="Enter Email" />
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for "personPhone">Primary Phone #:</label>
<input type="text" class="form-control" id="primaryPhone" name="primaryPhone" placeholder="Enter Phone #" />
</div>
</div>
</div>
</div>
<div id="newRowButton">
<div class="row">
<div class="col-md-1">
<button type="button" class="btn btn-success pull-left" onClick="addNewBandRow();">+</button>
</div>
<div id="remover" onClick="removeNewBandRow();" ></div>
<div class="col-md-1">
</div>
<div class="col-md-7">
</div>
<div class="col-md-3 padding-top-10">
<button type="submit" class="btn btn-primary pull-right" align="right">Submit</button>
</div>
</div>
</div>
</form>
</body>
</html>

At a high level, here are the steps you will need to implement:
Generate the HTML for the new red button.
This new red button will be hidden and unhidden based on a condition.
Example:
if (condition) {
$('#secondRedButton').hide();
} else {
$('#secondRedButton').show();
}
http://api.jquery.com/hide/
Bind an event handler to the "click" JavaScript event
Example:
$('#secondRedButton').click(function() {
// do something
});
https://api.jquery.com/click/
Please let me know if this helps.

You might as well use simple hiding statements as this:
var band_i = 0;
function addNewBandRow(con){
var e = con.getAttribute('name');
var c = document.getElementById('delBtn');
if(e == 'addRowBtn'){
band_i++;
var bandDiv = document.createElement('div');
bandDiv.innerHTML = '<div class="row" id="' + band_i + '"><div class = "col-md-3"><input type="text" class="form-control" id="newBandName' + band_i + '" name="newBandName' + band_i + '" placeholder="Enter Band Name"/></div><div class="col-md-3"><input type="text" class="form-control" id="primaryContact' + band_i + '" name="primaryContact' + band_i + '" placeholder="Enter Name"/></div> <div class="col-md-3"><input type="email" class="form-control" id="primaryEmail' + band_i + '" name="primaryEmail' + band_i + '" placeholder="Enter Email"/></div><div class="col-md-3"><input type="text" class="form-control" id="primaryPhone' + band_i + '" name="primaryPhone' + band_i + '" placeholder="Enter Phone #"/></div></div><br>';
document.getElementById('newBandRows').appendChild(bandDiv);
if(band_i != 0){
c.style.display = 'block';
}
}
}
function removeBandRow(con){
var e = con.getAttribute('name');
var c = document.getElementById('delBtn');
if(e == 'delRowBtn'){
var container = document.getElementById("newBandRows")
var nodes = container.childNodes;
container.removeChild(nodes[nodes.length - 1]);
band_i--;
if(band_i == 0)
c.style.display = 'none';
}
}
And modify buttons using this attributes.
<div class="col-md-1">
<button type="button" name="addRowBtn" class="btn btn-success pull-left" onClick="addNewBandRow(this);">+</button>
<button type="button" name="delRowBtn" id="delBtn" class="btn btn-danger pull-left" onClick="removeBandRow(this);" style='display:none' >-</button>
</div>

This should work for removing last child.
function removeBandRow(){
var container = document.getElementById("newBandRows")
var children = container.childNodes;
container.removeChild(children[children.length - 1]);
}

Related

How to transfer data from a form for Whatsapp to another page before submitting

I created a form in HTML that sends the data to WhstsApp, but I need that before going directly to WhatsApp, go through another page so that I can put the Google Ads conversion code.
Here's a print of the configuration:
https://prnt.sc/qlG3cVC_CzjG
Code:
<div class="row register-form">
<div class="col-md-12">
<form autocomplete="off">
<div class="form-group">
<input
type="text"
name="Name"
id="name"
class="form-control"
placeholder="Seu Nome *"
value=""
required=""
style="width: 100%;margin-bottom: 5px;"
/>
</div>
<div class="form-group">
<input
type="text"
name="Email"
id="email"
class="form-control"
placeholder="Seu E-mail *"
value=""
required=""
style="width: 100%;margin-bottom: 5px;"
/>
</div>
<div class="form-group">
<input
type="number"
name="Phone"
id="phone"
class="form-control"
placeholder="Seu Telefone*"
value=""
required=""
style="width: 100%;margin-bottom: 5px;"
/>
</div>
<div class="form-group">
<select class="form-control" id="service">
<option>Motivo do Contato</option>
<option>Quero um Orçamento</option>
<option>Outros Assuntos</option>
</select>
</div>
<div class="form-group">
<input
type="submit"
onclick='gotowhatsapp()'
name="submit"
id="submit"
class="btnSubmit btn-block"
value="ENVIAR"
/>
</div>
</form>
</div>
</div>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
function gotowhatsapp() {
var name = document.getElementById("name").value;
var phone = document.getElementById("phone").value;
var email = document.getElementById("email").value;
var service = document.getElementById("service").value;
var url = "https://wa.me/5511981252689?text="
+ "*Nome*: " + name + "%0a"
+ "*Telefone*: " + phone + "%0a"
+ "*E-mail*: " + email + "%0a"
+ "*Motivo*: " + service;
window.open(url, '_blank').focus();
}
How can I make this data go to another page and then redirect to WhatsApp?
change this your script js, example :
<script>
function gotowhatsapp() {
var name = document.getElementById("name").value;
var nohp = document.getElementById("nohp").value;
var pesan = document.getElementById("pesan").value;
var url = "https://api.whatsapp.com/send?phone="+ nohp +"&text="
+ "Nama: " + name + "%0a"
+ "Nohp: " + nohp + "%0a"
+ "Isi Pesan: " + pesan;
window.open(url, '_blank').focus();
}
</script>
hope can help you

proplem in jquery when creating inputs cannot create a limit for the created elements

I am trying to create inputs with jquery when user click on specific button as i create the inputs i want them to stop creating if the number of inputs exceeds 10
and here is the code
<script>
$(document).ready(function(){
var inputs = $('.product-options').length;
var max_inputs = 15;
var i=inputs;
var number = inputs;
if(inputs < 2){
$('.add_field_button').click(function(e){
e.preventDefault();
number++
i++;
$('.form-product').append('<span id="row'+i+'" class="myinput" style="transition:1s ease;"><div class="form-group"> <div class="col-sm-7"> <input type="text" class="form-control product-options" name="childen'+number+'"'+'value="" placeholder="the option"></div><div class="col-sm-3"> <input type="text" class="form-control product-options" name="childprice'+number+'"'+ 'value="" placeholder="option price"></div> </div> <div class="form-group"> <div class="col-sm-7"> <input type="text" class="form-control product-options" name="childsrb'+number+'"'+'value="" placeholder="the option in serbian"></div><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove"><i class="fas fa-times"></i></button></div></span>');
});
}
$(document).on('click', '.btn_remove', function(){
var button_id = $(this).attr("id");
$('#row'+button_id+'').remove();
number--
i--;
});
});
</script>
html code
<div class="form-group product-option">
<label class="col-sm-2 control-label"></label>
<div class="col-sm-10 product-option">
<button type="button" class="add_field_button on-hover" style="background: none; border:none;">
<i class="fas fa-plus on-hover" style="cursor: pointer"></i></button>
<label for="option">Product options</label><br>
<div class="form-group product-option form-product">
</div>
</div>
</div>
You can use an if statement to check whether i is smaller than 11:
$(document).ready(function() {
var inputs = $('.product-options').length;
var max_inputs = 15;
var i = inputs;
var number = inputs;
if (inputs < 2) {
$('.add_field_button').click(function(e) {
e.preventDefault();
number++
i++;
if (i < 11) {
$('.form-product').append('<span id="row' + i + '" class="myinput" style="transition:1s ease;"><div class="form-group"> <div class="col-sm-7"> <input type="text" class="form-control product-options" name="childen' + number + '"' + 'value="" placeholder="the option"></div><div class="col-sm-3"> <input type="text" class="form-control product-options" name="childprice' + number + '"' + 'value="" placeholder="option price"></div> </div> <div class="form-group"> <div class="col-sm-7"> <input type="text" class="form-control product-options" name="childsrb' + number + '"' + 'value="" placeholder="the option in serbian"></div><button type="button" name="remove" id="' + i + '" class="btn btn-danger btn_remove"><i class="fas fa-times"></i></button></div></span>');
}
});
}
$(document).on('click', '.btn_remove', function() {
var button_id = $(this).attr("id");
$('#row' + button_id + '').remove();
number--
i--;
});
});
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" integrity="sha512-iBBXm8fW90+nuLcSKlbmrPcLa0OT92xO1BIsZ+ywDWZCvqsWgccV3gFoRBv0z+8dLJgyAHIhR35VZc2oM/gI1w==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group product-option">
<label class="col-sm-2 control-label"></label>
<div class="col-sm-10 product-option">
<button type="button" class="add_field_button on-hover" style="background: none; border:none;">
<i class="fas fa-plus on-hover" style="cursor: pointer"></i></button>
<label for="option">Product options</label><br>
<div class="form-group product-option form-product">
</div>
</div>
</div>

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

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?

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>

Dynamic forms with dynamic elements with related array index

Note: Newbie to javascript and PHP
Requirement:
User has the option to add multiple forms and multiple levels as shown in the image.
structure:
idnum = 0
next = 1;
dimandlevels = [{}];
$(document).on('click', '.addlevel', function() {
clickedIdnum = $(this).data('idnum');
//console.log(idnum+'\n');
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + clickedIdnum + next);
newTextBoxDiv.after().html('<input class="input form-control textboxclass" id="textbox' + next + '" name="dimdetail[' + idnum + '][2][' + next + ']" type="text" placeholder="Enter Level ' + (next + 1) + ' value ">');
newTextBoxDiv.appendTo(".TextBoxesGroup" + idnum);
next++;
});
$(document).on('click', '.removelevel', function() {
if (next == 1) {
alert("No more textbox to remove");
return false;
}
next--;
$("#TextBoxDiv" + next).remove();
});
<h3><b>Create Texts</b></h3> <br>
<form class="form-horizontal" name="add_form" id="add_form">
<fieldset>
<form class="form-horizontal" role="form">
<fieldset>
<legend>Enter Dimension Details</legend>
<form class="form-horizontal" role="form">
<div class="controls" id="vignetteform">
<div id="dimensionform0">
<div class="well">
<div class="row">
<label class="col-lg-3 control-label">Dimension Text:</label>
<div class="col-lg-9">
<div class="control-group">
<div class="controls">
<div>
<input class="form-control textboxclassdim" type="text" name="dimdetail[0][0]" />
</div>
</div>
</div>
</div>
</div>
<div class="row">
<label class="col-lg-3 control-label">Dimension Description:</label>
<div class="col-lg-9">
<div class="control-group">
<div class="controls">
<div>
<input class="form-control textboxclass" type="text" name="dimdetail[0][1]" />
</div>
</div>
</div>
</div>
</div>
<div class="row">
<label class="col-lg-3 control-label">Enter Level:</label>
<div class="col-lg-8 control-group levelgroup"><input type="hidden" name="count" value="1">
<div class="controls TextBoxesGroup0">
<div id="TextBoxDiv00">
<input class="form-control textboxclass" id="textbox" type="text" name="dimdetail[0][2][0]" placeholder="Enter Level 1 Value" />
</div>
</div>
<button class="btn btn-info addlevel" type="button">Add Level</button>
<button class="btn btn-info removelevel" type="button">Remove level</button>
<span id="error_message" class="text-danger"></span>
</div>
</div>
</div>
</div>
</div>
</form>
</fieldset>
</form>
<div class="row">
<div class="col-md-8">
<button class="btn btn-info adddimension" type="button">Add Dimension</button>
<button class="btn btn-info removedimension" type="button">Remove Dimension</button>
<input type="button" name="submit" id="submit" class="btn btn-primary" value="Send" />
</div>
</div>
</fieldset>
</form>
<script src="includes/js/addlevelform.js"></script>
<script src="includes/js/adddimensionform.js"></script>
$(document).ready(function(){
var next = 1;
$(".adddimension").click(function(){
var newDimensionFormDiv = $(document.createElement('div'))
.attr("id",'dimensionform' + next);
newDimensionFormDiv.after().html(
'<div class="well"><div class="row"><label class="col-lg-3 control-label">Dimension Text:</label><div class="col-lg-9"><div class="control-group"><div class="controls"><div> <input class="form-control textboxclassdim" type="text" name="dimdetail['+ next +'][0]" /></div></div></div></div></div><div class="row"><label class="col-lg-3 control-label">Dimension Description:</label><div class="col-lg-9"><div class="control-group"><div class="controls"><div><input class="form-control textboxclass" type="text" name="dimdetail['+ next +'][1]" /></div></div></div></div></div><div class="row"><label class="col-lg-3 control-label">Enter Level:</label><div class="col-lg-8 control-group levelgroup"><input type="hidden" name="count" value="1"><div class="controls TextBoxesGroup'+ next +'" ><div id="TextBoxDiv'+ next +'0"><input class="form-control textboxclass" id="textbox'+ next +'" type="text" name="dimdetail['+ next +'][2][0]" placeholder="Enter Level '+ next +' Value" /></div></div><button data-idnum="'+idnum+'" class="btn btn-info addlevel" type="button">Add Level</button><button class="btn btn-info removelevel" type="button">Remove level</button><span id="error_message'+ next +'" class="text-danger"></span></div></div></div></div>'
);
newDimensionFormDiv.appendTo("#vignetteform");
next++;
idnum++;
var jsonObj = {idnum:1};
dimandlevels.data.push(idnum:1);
console.log(dimandlevels);
});
$(".removedimension").click(function(){
if(next==1){
alert("No more dimension to remove");
return false;
}
next --;
idnum--;
$("#dimensionform" + next).remove();
});
});
Issue: 1. The add level works only on first form
2. And the array indexes should be proper
So i need a way such that i can create multiple dimensions with levels with proper level ids.
Thank you and sorry for my bad code !!!! I am very new to programming :/

Categories