Step by Step Modal bootstrap - javascript

I'm trying to make a MODAL step by step validating each step, but I can only validate the input with error, but I can not validate the select.
wanted that when the value of the select is equal to ZERO (0) the validation occurs as well.
Could someone help me with this JS? I would be extremely grateful.
$(document).ready(function () {
var navListItems = $('div.setup-panel div a'),
allWells = $('.setup-content'),
allNextBtn = $('.nextBtn');
allWells.hide();
navListItems.click(function (e) {
e.preventDefault();
var $target = $($(this).attr('href')),
$item = $(this);
if (!$item.hasClass('disabled')) {
navListItems.removeClass('btn-primary').addClass('btn-default');
$item.addClass('btn-primary');
allWells.hide();
$target.show();
$target.find('input:eq(0)').focus();
$target.find('select:eq(0)').focus();
}
});
allNextBtn.click(function(){
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),
curInputs = curStep.find("input[type='text'],input[type='url'],select[type='text']"),
isValid = true;
$(".form-group").removeClass("has-error");
for(var i=0; i<curInputs.length; i++){
if (!curInputs[i].validity.valid){
isValid = false;
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
if (isValid)
nextStepWizard.removeAttr('disabled').trigger('click');
});
$('div.setup-panel div a.btn-primary').trigger('click');
});
<div class="container">
<div class="row">
<h2>Multistep form wizard on modal</h2>
<div class="center"><button data-toggle="modal" data-target="#requestform" class="btn btn-primary center-block">Click Me</button></div>
</div>
</div>
<div class="modal fade" id="requestform" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h3 class="modal-title" id="lineModalLabel">Proposta</h3>
</div>
<div class="modal-body">
<!-- Steps starts here -->
<div class="requestwizard">
<div class="requestwizard-row setup-panel">
<div class="requestwizard-step">
1
<p>Selecione um contato</p>
</div>
<div class="requestwizard-step">
2
<p>Selecione um curso</p>
</div>
<div class="requestwizard-step">
3
<p>Forma de pagamento</p>
</div>
</div>
</div>
<br>
<form role="form">
<div class="row setup-content" id="step-1">
<div class="col-xs-12">
<div class="col-md-12">
<div class="form-group">
<input maxlength="100" type="text" required="required" class="form-control" placeholder="Contato" />
</div>
<hr>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Próximo</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-2">
<div class="col-xs-12">
<div class="col-md-12">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<select class="form-control custom-select" id="filtercountry">
<option value="0" class="selectcountry">Country</option>
<option value="201" class="selectcountry">Australia</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<select class="form-control custom-select" id="filtercity">
<option value="0" class="selectcity">City</option>
<option value="101" class="selectcity">California</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<select class="form-control custom-select" id="filterregion">
<option value="0" class="selectregion">Region</option>
<option value="3" class="selectregion">Brazil</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input maxlength="200" type="text" required="required" class="form-control" placeholder="Curso" />
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Próximo</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-3">
<div class="col-xs-12">
<div class="col-md-12">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><spring:message code="label.firstinstallment"/></label>
<input type="text" class="form-control" placeholder="First installment" id="finstallment" name="finstallment" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><spring:message code="label.numberparcels"/></label>
<select class="form-control custom-select" name="parcels" required>
<option value="0">0</option>
<option value="1">1</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><spring:message code="label.firstinvoice"/></label>
<input type="date" class="form-control" placeholder="Invoice maturity" name="expiration_date" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label"><spring:message code="label.selectpaymentplan"/></label>
<select class="form-control custom-select" name="payment_plan" required>
<option value="1">Bank slip</option>
</select>
</div>
</div>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Enviar</button>
</div>
</div>
</div>
</form>
<!-- Form ends here -->
</div>
</div>
</div>
</div>

you need to check for the control type in the for loop inside allNextBtn.click event like this:
for(var i=0; i<curInputs.length; i++){
//if the control is select check the selected index if it is ZERO
if ( $(curInputs[i]).is('select') && (curInputs[i].selectedIndex === 0)
{
isValid = false;
}
//else check control validity
else if (!curInputs[i].validity.valid)
{
isValid = false;
}
if(!isValid)
{
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
and change this line:
curInputs = curStep.find("input[type='text'],input[type='url'],select[type='text']"),
to this:
curInputs = curStep.find("input[type='text'],input[type='url'],select"),
here is the full js code:
$(document).ready(function () {
var navListItems = $('div.setup-panel div a'),
allWells = $('.setup-content'),
allNextBtn = $('.nextBtn');
allWells.hide();
navListItems.click(function (e) {
e.preventDefault();
var $target = $($(this).attr('href')),
$item = $(this);
if (!$item.hasClass('disabled')) {
navListItems.removeClass('btn-primary').addClass('btn-default');
$item.addClass('btn-primary');
allWells.hide();
$target.show();
$target.find('input:eq(0)').focus();
$target.find('select:eq(0)').focus();
}
});
allNextBtn.click(function(){
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),
curInputs = curStep.find("input[type='text'],input[type='url'],select"),
isValid = true;
$(".form-group").removeClass("has-error");
//BEGIN EDIT
for(var i=0; i<curInputs.length; i++){
//if the control is select check the selected index if it is ZERO
if ( $(curInputs[i]).is('select') && (curInputs[i].selectedIndex === 0))
{
isValid = false;
}
//else check control validity
else if (!curInputs[i].validity.valid)
{
isValid = false;
}
if(!isValid)
{
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
//END EDIT
if (isValid)
nextStepWizard.removeAttr('disabled').trigger('click');
});
$('div.setup-panel div a.btn-primary').trigger('click');
});

Related

Dynamically adding input fields JavaScript

I would like to enter two input fields and one button dynamically adding them from the button click function.
They should look like this:
https://i.stack.imgur.com/iRnDu.png
On click of the button add, I would like to disable the button, add a new row of items (2 input boxes and the clickable button again). I would also like to store the 2 values from the text-boxes in an array.
add() {
let row = document.createElement('div');
row.className = 'row';
row.innerHTML += `
<br>
<input type="text" id="text1"> <input type="text" id="text2"> <button id="button">ADD</button> `;
document.querySelector('.showInputField').appendChild(row);
document.getElementById("button").addEventListener('click',this.input,false);}input(){
let inputValue = (document.getElementById("text1") as HTMLInputElement).value;
console.log(inputValue);
this.user.push(inputValue);
this.users.push(this.user);
this.user = [];
}
And this is the HTML:
<div>
CLICK ON BUTTON TO ADD NEW FIELD
<div class="showInputField">
<button (click)="add()">ADD</button>
</div>
<!-- The add() function is called -->
</div>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<!------ Include the above in your HEAD tag ---------->
<div class="panel panel-default">
<div class="panel-body">
<div id="education_fields">
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<input type="text" class="form-control" id="Schoolname" name="Schoolname[]" value=""
placeholder="School name">
</div>
</div>
<div class="col-sm-3 nopadding">
<div class="form-group">
<div class="input-group">
<select class="form-control" id="educationDate" name="educationDate[]">
<option value="">Date</option>
<option value="2015">2015</option>
<option value="2016">2016</option>
<option value="2017">2017</option>
<option value="2018">2018</option>
</select>
<div class="input-group-btn">
<button class="btn btn-success" type="button" onclick="education_fields();"> <span
class="glyphicon glyphicon-plus" aria-hidden="true"></span> </button>
</div>
</div>
</div>
</div>
<div class="clear"></div>
</div>
</div>
<script>
var room = 1;
function education_fields() {
room++;
var objTo = document.getElementById('education_fields')
var divtest = document.createElement("div");
divtest.setAttribute("class", "form-group removeclass" + room);
var rdiv = 'removeclass' + room;
divtest.innerHTML = '<div class="col-sm-3 nopadding"><div class="form-group"> <input type="text" class="form-control" id="Schoolname" name="Schoolname[]" value="" placeholder="School name"></div></div><div class="col-sm-3 nopadding"><div class="form-group"><div class="input-group"> <select class="form-control" id="educationDate" name="educationDate[]"><option value="">Date</option><option value="2015">2015</option><option value="2016">2016</option><option value="2017">2017</option><option value="2018">2018</option> </select><div class="input-group-btn"> <button class="btn btn-danger" type="button" onclick="remove_education_fields(' + room + ');"> <span class="glyphicon glyphicon-minus" aria-hidden="true"></span> </button></div></div></div></div><div class="clear"></div>';
objTo.appendChild(divtest)
}
function remove_education_fields(rid) {
$('.removeclass' + rid).remove();
}
</script>

How to sum the values from dynamically created input fields

I have created Dynamic Add / Remove fields. Everything is working perfectly. I want sum of values from Amount field to be displayed on real time basis using JavaScript. I have tried but am unable to do. I am not much familiar with JavaScript.
Following is code:
var i = 0;
jQuery(document).ready(function($) {
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
return false;
});
});
var rows = '<div class="all-allocation-fields"><div class="row"><div class="col-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]"></div></div><div class="col-5"><div class="form-group"><input type="text" class="form-control code" id="code" name="allocate_amount[]"></div></div><div class="col-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields">Remove</button></div></div></div>';
//add input
$('#add-allocation-fields').click(function() {
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
<div class="card-header text-center">
<b>Allocation of Funds</b>
</div>
<div class="card-body">
<div class="row">
<div class="col-5"><label><b>Allocation Items</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-5"><label><b>Amount</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-2"></div>
</div>
<div class="row">
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_items[]">
</div>
</div>
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control code" id="code" name="allocate_amount[]">
</div>
</div>
<div class="col-2">
<button type="button" class="btn btn-success" id="add-allocation-fields">Add</button>
</div>
</div>
<div id="fund-allocation-fields">
</div>
<small class="form-text text-muted"><i>Total amount must be equal to the goal amount.</i></small>
<div id="sum"></div>
</div>
</div>
You can use add keyup event listener and calculate sum as:
function calculateSum() { //Add a calculateSum function
var sum = 0;
$("input[name='allocate_amount[]']").each(function() {
sum += +this.value || 0;
});
$("#sum").text(sum);
}
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
calculateSum(); //Call calculateSum to update the sum valaue
return false;
});
});
$("body").on("keyup", "input[name='allocate_amount[]']", calculateSum); //update when keyup
Demo:
var i = 0;
jQuery(document).ready(function($) {
function calculateSum() {
var sum = 0;
$("input[name='allocate_amount[]']").each(function() {
sum += +this.value || 0;
});
$("#sum").text(sum);
}
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
calculateSum();
return false;
});
});
var rows = '<div class="all-allocation-fields"><div class="row"><div class="col-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]"></div></div><div class="col-5"><div class="form-group"><input type="text" class="form-control code" id="code" name="allocate_amount[]"></div></div><div class="col-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields">Remove</button></div></div></div>';
//add input
$('#add-allocation-fields').click(function() {
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
return false;
});
$("body").on("keyup", "input[name='allocate_amount[]']", calculateSum);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card">
<div class="card-header text-center">
<b>Allocation of Funds</b>
</div>
<div class="card-body">
<div class="row">
<div class="col-5"><label><b>Allocation Items</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-5"><label><b>Amount</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-2"></div>
</div>
<div class="row">
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control" name="allocate_items[]">
</div>
</div>
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control code" id="code" name="allocate_amount[]">
</div>
</div>
<div class="col-2">
<button type="button" class="btn btn-success" id="add-allocation-fields">Add</button>
</div>
</div>
<div id="fund-allocation-fields">
</div>
<small class="form-text text-muted"><i>Total amount must be equal to the goal amount.</i></small>
<div id="sum"></div>
</div>
</div>
I think you can do it with this code:
function calcAmount(){
var amount = 0;
$('input[name="allocate_amount[]"]').each(function(){
amount = amount + $(this).val();
});
return amount;
}
jQuery(document).ready(function($) {
$("input[name="allocate_amount[]]").blur(function(){
$("#sum").html(calcAmount());
});
});
Okay, I try to update your code: and it works fine:
main changes:
- assign ids to input fields
- make changes in function
have a look to jsfiddle
https://jsfiddle.net/dupinderdhiman/ygvphmxq/31/
Main changes:
var sum = eval($('#value1').val()) + eval($('#value2').val());
$('#sum').text(sum);
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").click(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<div class="card">
<div class="card-header text-center">
<b>Allocation of Funds</b>
</div>
<div class="card-body">
<div class="row">
<div class="col-5"><label><b>Allocation Items</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-5"><label><b>Amount</b> <b style="color:#FF0000;">*</b></label></div>
<div class="col-2"></div>
</div>
<div class="row">
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control" id='value1' name="allocate_items[]">
</div>
</div>
<div class="col-5">
<div class="form-group">
<input type="text" class="form-control code" id='value2' name="allocate_amount[]">
</div>
</div>
<div class="col-2">
<button type="button" class="btn btn-success" id="add-allocation-fields">Add</button>
</div>
</div>
<div id="fund-allocation-fields">
</div>
<small class="form-text text-muted"><i>Total amount must be equal to the goal amount. <span id="sum"></span></i></small>
</div>
</div>
<script type="text/javascript">
var i = 0;
jQuery(document).ready(function($) {
//fadeout selected item and remove
$(document).on('click', '#remove-allocation-fields', function(event) {
event.preventDefault();
$(this).parent().fadeOut(300, function() {
$(this).parent().empty();
return false;
});
});
var rows = '<div class="all-allocation-fields"><div class="row"><div class="col-5"><div class="form-group"><input type="text" class="form-control" name="allocate_items[]"></div></div><div class="col-5"><div class="form-group"><input type="text" class="form-control code" id="code" name="allocate_amount[]"></div></div><div class="col-2"><button type="button" class="btn btn-danger" id="remove-allocation-fields">Remove</button></div></div></div>';
//add input
$('#add-allocation-fields').click(function() {
debugger;
$(rows).fadeIn("slow").appendTo('#fund-allocation-fields');
i++;
var sum = eval($('#value1').val()) + eval($('#value2').val());
$('#sum').text(sum);
return false;
});
});
</script>
</body>
</html>

Javascript - Multi-step form doesn't work, "next" button won't work

I have to make a multi-step form for a website.
I've used HTML, CSS and JS, but the JS seems to not work.
The "Next" button is not working at all.
On the website all the questions appear together, but I have to do something different.
The "next" button has to let other question appear when pushed, but is not like that.
Can you help me? Maybe I included the js in the worng way?
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Richiedi qui il tuo preventivo</h4>
</div>
<div class="modal-body">
<div class="top-content">
<div class="inner-bg">
<div class="container">
<div class="row">
<div class="col-sm-5">
<div class="description">
</div>
</div>
</div>
<div class="row">
<div class="col-sm-5 form-box">
<form role="form" action="" method="post" class="registration-form">
<fieldset>
<div class="form-top">
<div class="form-top-left">
<h3>Parte 1</h3>
<p>Racontati chi sei:</p>
</div>
<div class="form-top-right">
<i class="fa fa-user"></i>
</div>
</div>
<div class="form-bottom">
<div class="form-group">
<label class="sr-only" for="form-first-name">Nome</label>
<input type="text" name="form-first-name" placeholder="Nome" class="form-first-name form-control" id="form-first-name">
</div>
<div class="form-group">
<label class="sr-only" for="form-last-name">Cognome</label>
<input type="text" name="form-last-name" placeholder="Cognome" class="form-last-name form-control" id="form-last-name">
</div>
<div class="form-group">
<label class="sr-only" for="form-about-yourself">Nome della tua attività</label>
<textarea name="form-about-yourself" placeholder="Nome della tua attività"
class="form-about-yourself form-control" id="form-about-yourself"></textarea>
</div>
<button type="button" class="btn btn-next">Avanti</button>
</div>
</fieldset>
<fieldset>
<div class="form-top">
<div class="form-top-left">
<h3>Parte 2</h3>
<p>Le tue informazioni di contatto:</p>
</div>
<div class="form-top-right">
<i class="fa fa-key"></i>
</div>
</div>
<div class="form-bottom">
<div class="form-group">
<label class="sr-only" for="form-email">Email</label>
<input type="text" name="form-email" placeholder="Email" class="form-email form-control" id="form-email">
</div>
<div class="form-group">
<label class="sr-only" for="form-number">Numero di telefono</label>
<input type="number" name="form-number" placeholder="Numero di telefono" class="form-password form-control" id="form-password">
</div>
<!--<div class="form-group">
<label class="sr-only" for="form-repeat-password">Repeat password</label>
<input type="password" name="form-repeat-password" placeholder="Repeat password..."
class="form-repeat-password form-control" id="form-repeat-password">
</div>-->
<button type="button" class="btn btn-previous">Indietro</button>
<button type="button" class="btn btn-next">Avanti</button>
</div>
</fieldset>
<fieldset>
<div class="form-top">
<div class="form-top-left">
<h3>Parte 3</h3>
<p>Dobbiamo avere ancora qualche informazione prima di calcolare il tuo preventivo:</p>
</div>
</div>
<div class="form-bottom">
<div class="form-group">
<label class="sr-only" for="form-number">Quante persone servi al giorno?</label>
<input type="text" name="form-facebook" placeholder="Numero" class="form-facebook form-control" id="form-question">
</div>
<div class="form-group">
<label class="sr-only" for="form-question">Compri bottiglie di plastica o di vetro?</label>
<input type="text" name="form-twitter" placeholder="Bottiglie di plastica o di vetro?" class="form-question form-control" id="form-question">
</div>
<button type="button" class="btn btn-previous">Indietro</button>
<button type="submit" class="btn">Calcola!</button>
</div>
</fieldset>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
+function($) {
'use strict';
var modals = $('.modal.multi-step');
modals.each(function(idx, modal) {
var $modal = $(modal);
var $bodies = $modal.find('div.modal-body');
var total_num_steps = $bodies.length;
var $progress = $modal.find('.m-progress');
var $progress_bar = $modal.find('.m-progress-bar');
var $progress_stats = $modal.find('.m-progress-stats');
var $progress_current = $modal.find('.m-progress-current');
var $progress_total = $modal.find('.m-progress-total');
var $progress_complete = $modal.find('.m-progress-complete');
var reset_on_close = $modal.attr('reset-on-close') === 'true';
function reset() {
$modal.find('.step').hide();
$modal.find('[data-step]').hide();
}
function completeSteps() {
$progress_stats.hide();
$progress_complete.show();
$modal.find('.progress-text').animate({
top: '-2em'
});
$modal.find('.complete-indicator').animate({
top: '-2em'
});
$progress_bar.addClass('completed');
}
function getPercentComplete(current_step, total_steps) {
return Math.min(current_step / total_steps * 100, 100) + '%';
}
function updateProgress(current, total) {
$progress_bar.animate({
width: getPercentComplete(current, total)
});
if (current - 1 >= total_num_steps) {
completeSteps();
} else {
$progress_current.text(current);
}
$progress.find('[data-progress]').each(function() {
var dp = $(this);
if (dp.data().progress <= current - 1) {
dp.addClass('completed');
} else {
dp.removeClass('completed');
}
});
}
function goToStep(step) {
reset();
var to_show = $modal.find('.step-' + step);
if (to_show.length === 0) {
// at the last step, nothing else to show
return;
}
to_show.show();
var current = parseInt(step, 10);
updateProgress(current, total_num_steps);
findFirstFocusableInput(to_show).focus();
}
function findFirstFocusableInput(parent) {
var candidates = [parent.find('input'), parent.find('select'),
parent.find('textarea'),parent.find('button')],
winner = parent;
$.each(candidates, function() {
if (this.length > 0) {
winner = this[0];
return false;
}
});
return $(winner);
}
function bindEventsToModal($modal) {
var data_steps = [];
$('[data-step]').each(function() {
var step = $(this).data().step;
if (step && $.inArray(step, data_steps) === -1) {
data_steps.push(step);
}
});
$.each(data_steps, function(i, v) {
$modal.on('next.m.' + v, {step: v}, function(e) {
goToStep(e.data.step);
});
});
}
function initialize() {
reset();
updateProgress(1, total_num_steps);
$modal.find('.step-1').show();
$progress_complete.hide();
$progress_total.text(total_num_steps);
bindEventsToModal($modal, total_num_steps);
$modal.data({
total_num_steps: $bodies.length,
});
if (reset_on_close){
//Bootstrap 2.3.2
$modal.on('hidden', function () {
reset();
$modal.find('.step-1').show();
})
//Bootstrap 3
$modal.on('hidden.bs.modal', function () {
reset();
$modal.find('.step-1').show();
})
}
}
initialize();
})
}(jQuery);

Duplicate html form field rows with button in javascript

Im trying to duplicate this entire form field when I click on the "Add Row" button. For some reason when I reload the page, the second row I'm trying to duplicate appears and the button click to "Add row" that fires up the function doesn't work either. I'm obviously doing something wrong here?
var counter = 0;
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'row';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields, insertHere);
}
window.onload = moreFields;
<div class="row" id="readroot">
<div class="col-lg-2">
<div class="md-form form-sm new_row">
<input type="text" name="fullname[]" placeholder="Full Name" class="form-control" required>
</div>
</div>
<div class="col-lg-2">
<div class="form-sm">
<select name="gnation[]" id="national" class="mdb-select person-title grey-text" required>
<option value="" disabled selected> Nationality </option>
<option value="afghan">Afghan</option>
<option value="albanian">Albanian</option>
<option value="algerian">Algerian</option>
<option value="american">American</option>
<option value="andorran">Andorran</option>
<option value="angolan">Angolan</option>
<!-- a lot more -->
<option value="zambian">Zambian</option>
<option value="zimbabwean">Zimbabwean</option>
</select>
<label for="national"></label>
</div>
</div>
<div class="col-lg-2">
<div class="md-form form-sm new_row">
<input type="text" name="contact[]" placeholder="Contact" class="form-control" required>
</div>
</div>
<div class="col-lg-2">
<div class="md-form form-sm new_row">
<input type="text" name="gemail[]" placeholder="Email" class="form-control" required>
</div>
</div>
<div class="col-lg-2">
<div class="md-form form-sm new_row">
<input type="text" name="gorganisation[]" placeholder="Organisation" class="form-control" required>
</div>
</div>
<div class="col-lg-2">
<div class="md-form form-sm">
<a onclick="this.moreFields();" id="moreFields" class="btn btn-sm btn-primary waves-effect waves-light">Add Row</a>
</div>
</div>
</div>
<div class="row" id="writeroot"></div>
<input type="button" class="btn btn-sm btn-danger waves-effect waves-light pull-right" value="Remove" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">
There were couple of issue;
add row has id="morefields"; on duplicating we will have two elements with same id; this is not good;
so i add morefields to class; Also on adding new row, script doesnt know that new html element has been created with class "morefields";
so i placed the eventlistener inside a function and I am invoking it on two occasions
1) on page load
2) on click of add row (with a small timeout).
thus when add row, new row is created and the 'add row' anchor is binded with correct event listener
var counter = 0;
//document.getElementById('moreFields').onclick = moreFields;
window.onload = loadEventListener();
function loadEventListener() {
let addRowAnchorTags = document.getElementsByClassName('moreFields');
for(i=0;i<addRowAnchorTags.length; i++) {
addRowAnchorTags[i].onclick = moreFields;
}
}
function moreFields() {
counter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'row';
var newField = newFields.childNodes;
for (var i = 0; i < newField.length; i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + counter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields, insertHere);
setTimeout(function() {loadEventListener();})
}
//window.onload = moreFields;
<div class="row" id="readroot">
<div class="col-lg-2">
<div class="md-form form-sm new_row">
<input type="text" name="fullname[]" placeholder="Full Name" class="form-control" required>
</div>
</div>
<div class="col-lg-2">
<div class="form-sm">
<select name="gnation[]" id="national" class="mdb-select person-title grey-text" required>
<option value="" disabled selected> Nationality </option>
<option value="afghan">Afghan</option>
<option value="albanian">Albanian</option>
<option value="algerian">Algerian</option>
<option value="american">American</option>
<option value="andorran">Andorran</option>
<option value="angolan">Angolan</option>
<!-- a lot more -->
<option value="zambian">Zambian</option>
<option value="zimbabwean">Zimbabwean</option>
</select>
<label for="national"></label>
</div>
</div>
<div class="col-lg-2">
<div class="md-form form-sm new_row">
<input type="text" name="contact[]" placeholder="Contact" class="form-control" required>
</div>
</div>
<div class="col-lg-2">
<div class="md-form form-sm new_row">
<input type="text" name="gemail[]" placeholder="Email" class="form-control" required>
</div>
</div>
<div class="col-lg-2">
<div class="md-form form-sm new_row">
<input type="text" name="gorganisation[]" placeholder="Organisation" class="form-control" required>
</div>
</div>
<div class="col-lg-2">
<div class="md-form form-sm">
<a id="moreFields" class=" moreFields btn btn-sm btn-primary waves-effect waves-light">Add Row</a>
</div>
</div>
</div>
<div class="row" id="writeroot"></div>
<input type="button" class="btn btn-sm btn-danger waves-effect waves-light pull-right" value="Remove" onclick="this.parentNode.parentNode.removeChild(this.parentNode);">

Jquery button don't append elements with no errors at the console

I have this html form:
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
<div class="row clonedInput" id="clonedInput1">
<div class="col-sm-6">
<label for="diagnosis_data">Medication</label>
<fieldset class="form-group">
<select class="form-control select" name="diagnosis_data" id="diagnosis_data">
<option value="choose">Select</option>
</select>
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<div class="col-sm-6">
<label for="patient_weight">Quantity</label>
<fieldset class="form-group">
<input type="number" class="form-control" name="patient_weight" id="patient_weight">
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<!-- End class="col-sm-6" -->
</div>
<div class="actions pull-right">
<button class="btn btn-danger clone">Add More</button>
<button class="btn btn-danger remove">Remove</button>
</div>
And this jQuery Script from this link here:
<script>
$(document).ready(function()
{
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
})
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
function clone(){
$(this).parents(".clonedInput").clone()
.appendTo(".rounded")
.attr("id", "clonedInput" + cloneIndex)
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
cloneIndex++;
}
function remove(){
$(this).parents(".clonedInput").remove();
}
</script>
But of course with changes to html but nothing happens when I click on each of the buttons, even no errors at the console. Here is my fiddle.
I am using jQuery 3.2.1
EDIT 1
I tried this script:
$("button.clone").on("click", function()
{
$('.clonedInput').clone().insertAfter('.clonedInput')
});
it works but there is 2 problems:
ID of each element is not incrementing;
If I had 2 elements and clicked on the button they will be 4, then 8, then...
EDIT 2
I tried this and the problem number 2 is gone:
$("button.clone").on("click", function()
{
$('#clonedInput1').clone().insertAfter('#clonedInput1')
});
Now I still have to increment the id so I can send the data later using Ajax. Here is my updated fiddle.
If you're open to hyphenating the id's:
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = 1;
function clone(){
cloneIndex++;
$(this).parents(".clonedInput").clone()
.appendTo("body")
.attr("id", 'clonedInput-'+(cloneIndex))
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = id.split('-')[0] +'-'+(cloneIndex);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
}
function remove(){
$(this).parents(".clonedInput").remove();
}
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clonedInput-1" class="clonedInput">
<div>
<label for="txtCategory" class="">Learning category <span class="requiredField">*</span></label>
<select class="" name="txtCategory[]" id="category-1">
<option value="">Please select</option>
</select>
</div>
<div>
<label for="txtSubCategory" class="">Sub-category <span class="requiredField">*</span></label>
<select class="" name="txtSubCategory[]" id="subcategory-1">
<option value="">Please select category</option>
</select>
</div>
<div>
<label for="txtSubSubCategory">Sub-sub-category <span class="requiredField">*</span></label>
<select name="txtSubSubCategory[]" id="subsubcategory-1">
<option value="">Please select sub-category</option>
</select>
</div>
<div class="actions">
<button class="clone">Clone</button>
<button class="remove">Remove</button>
</div>
</div>
Check if below code works!
$(document).ready(function()
{
$("button.clone").on("click", clone);
$("button.remove").on("click", remove);
})
var regex = /^(.+?)(\d+)$/i;
var cloneIndex = $(".clonedInput").length;
function clone(){
$(this).closest(".rounded").clone()
.insertAfter(".rounded:last")
.attr("id", "rounded" + (cloneIndex+1))
.find("*")
.each(function() {
var id = this.id || "";
var match = id.match(regex) || [];
if (match.length == 3) {
this.id = match[1] + (cloneIndex+1);
}
})
.on('click', 'button.clone', clone)
.on('click', 'button.remove', remove);
cloneIndex++;
}
function remove(){
$(this).parent().parent(".rounded").remove();
}
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<div class="col-sm-4 rounded" style="background-color: #D3D3D3">
<div class="row clonedInput" id="clonedInput1">
<div class="col-sm-6">
<label for="diagnosis_data">Medication</label>
<fieldset class="form-group">
<select class="form-control select" name="diagnosis_data" id="diagnosis_data">
<option value="choose">Select</option>
</select>
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<div class="col-sm-6">
<label for="patient_weight">Quantity</label>
<fieldset class="form-group">
<input type="number" class="form-control" name="patient_weight" id="patient_weight">
</fieldset>
<!-- End class="col-sm-6" -->
</div>
<!-- End class="col-sm-6" -->
</div>
<div class="actions pull-right">
<button class="btn btn-danger clone">Add More</button>
<button class="btn btn-danger remove">Remove</button>
</div>
You are missing the parent div. As you are doing in clone() :
$(this).parents(".clonedInput").clone()
But in your html <div class="clonedInput" id="clonedInput1"> is not parent of <button class="btn btn-danger clone">Add More</button>.
Here is the updated fiddle - https://jsfiddle.net/b9L4k8mL/2/

Categories

Resources