Hide empty inputs in a dynamic form - javascript

When I am returning the dynamic form, I intend to hide the inputs when it returns an empty or null value.
For example, how can you retron the lines:
Id = 1 NumCap = 1 Capitulo = teste
Id = 2 NumCap = Capitulo =
Id = 3 NumCap = 2 Capitulo = teste1
When returning the form, when returning the line with Id = 2, hide the two inputs, because they come empty.
I return the form as follows:
success:function(data1){
var linha1 = ``;
for (var i = 0; i < data1.length; i++) {
Id = data1[i][0];
NumCap = data1[i][14];
Capitulo = data1[i][15];
linha1 += `<div class="teste1">
<div class="form-group col-md-2 testeeeee">
<input type="text" class="form-control1 alinha" name="Capitul[]" value="${NumCap}">
<span class="form-highlight"></span>
<span class="form-bar"></span>
<label class="label3" for="Capitulo">Nº Capitulo</label>
</div>
<div class="form-group col-md-4 testeeeee">
<input type="text" class="form-control1" name="Capitul1[]" value="${Capitulo}">
<span class="form-highlight"></span>
<span class="form-bar"></span>
<label class="label1" for="Capitulo">Capitulo</label>
</div>
</div>
}
I am trying to put this code before starting the form return:
if(!NumCap && !Capitulo){
$('.testeeeee').show();
}else{
$('.testeeeee').hide();
}
But it does not work.

success:function(data1){
var linha1 = ``;
Object.keys(data1).forEach(i=>{
Id = data1[i][0];
NumCap = data1[i][14];
Capitulo = data1[i][15];
if(!Id.length||!NumCap.length||!Capitulo.length){return;} //if any length of these values are 0, don't put them into linha1
linha1 += `<div class="teste1">
<div class="form-group col-md-2 testeeeee">
<input type="text" class="form-control1 alinha" name="Capitul[]" value="${NumCap}">
<span class="form-highlight"></span>
<span class="form-bar"></span>
<label class="label3" for="Capitulo">Nº Capitulo</label>
</div>
<div class="form-group col-md-4 testeeeee">
<input type="text" class="form-control1" name="Capitul1[]" value="${Capitulo}">
<span class="form-highlight"></span>
<span class="form-bar"></span>
<label class="label1" for="Capitulo">Capitulo</label>
</div>
</div>`
})
}

You can use this to check blank value and hide the textbox
if(jQuery(".testeeeee > .form-control1").length > 0){
$(".testeeeee > .form-control1").each(function(){
if($(this).val() == ''){
$(this).hide();
}else{
console.log("TEXTBOX IS NOT EMPTY \t \n");
$(this).show();
}
});
}
let me know if this helps you.

Related

Adding and removing numbers from the total box onchange

I am trying to add and remove the price when the check box is checked and unchecked. I am using an event listener function but it is not working how I want it to. How will I be able to click on either of the check boxes to add to the total and remove when unchecked?
HTML:
window.addEventListener('load', function() {
'use strict';
const form = document.getElementById('orderForm');
form.addEventListener("change", function() {
var total = 0;
const checkboxes = form.querySelectorAll('input[data-price][type=checkbox]');
const checkboxCount = checkboxes.length;
for (let i = 0; i < checkboxCount; i++) {
const checkbox = checkboxes[i];
if (checkbox.checked) {
total += parseFloat(checkbox.dataset.price);
form.total.value = total;
var boxTotal = parseFloat(total);
boxTotal = boxTotal.toFixed(2);
form.total.value = boxTotal;
} else {
form.total.value -= this.value;
}
}
});
});
<form id="orderForm">
<section id="selectRecords">
<div class="item">
<span class="price">10.80</span>
<span class="chosen"><input type="checkbox" data-price="9.80"></span>
</div>
<div class="item">
<span class="price">15.70</span>
<span class="chosen"><input type="checkbox" data-price="12.70"></span>
</div>
<div class="item">
<span class="price">18.20</span>
<span class="chosen"><input type="checkbox" data-price="8.20"></span>
</div>
</section>
<section id="checkCost">
Total <input type="text" name="total" size="10" readonly="">
</section>
</section>
</form>
Because you're summing up all checkboxes associated prices on change, you shouldn't have the } else { form.total.value -= this.value; - not only does this refer to the form (which doesn't have a .value), you also don't care at all about the unchecked prices, because they don't affect final value after a change event anyway.
You can select only the checked checkboxes in your query string with the :checked psuedo-selector - this will let you leave out the if (checkbox.checked) part.
You also might consider coming up with the total number once, and then assigning to the input's value once, rather than on every iteration:
const form = document.getElementById('orderForm');
form.addEventListener("change", function() {
let total = 0;
const checkboxes = form.querySelectorAll('input[data-price][type=checkbox]:checked');
const checkboxCount = checkboxes.length;
for (let i = 0; i < checkboxCount; i++) {
const checkbox = checkboxes[i];
total += Number(checkbox.dataset.price);
}
form.total.value = total.toFixed(2);
});
<form id="orderForm">
<section id="selectRecords">
<div class="item">
<span class="price">10.80</span>
<span class="chosen"><input type="checkbox" name="record[]" value="973" data-price="9.80"></span>
</div>
<div class="item">
<span class="price">15.70</span>
<span class="chosen"><input type="checkbox" name="record[]" value="974" data-price="12.70"></span>
</div>
<div class="item">
<span class="price">18.20</span>
<span class="chosen"><input type="checkbox" name="record[]" value="975" data-price="8.20"></span>
</div>
</section>
<section id="checkCost">
Total <input type="text" name="total" size="10" readonly="">
</section>
</section>
</form>
Also, to be a bit more functional, you might use Array.prototype.reduce to calculate the total, rather than a for loop:
const form = document.getElementById('orderForm');
form.addEventListener("change", function() {
const total = Array.prototype.reduce.call(
form.querySelectorAll('input[data-price][type=checkbox]:checked'),
(a, checkbox) => a + Number(checkbox.dataset.price),
0
);
form.total.value = total.toFixed(2);
});
<form id="orderForm">
<section id="selectRecords">
<div class="item">
<span class="price">10.80</span>
<span class="chosen"><input type="checkbox" name="record[]" value="973" data-price="9.80"></span>
</div>
<div class="item">
<span class="price">15.70</span>
<span class="chosen"><input type="checkbox" name="record[]" value="974" data-price="12.70"></span>
</div>
<div class="item">
<span class="price">18.20</span>
<span class="chosen"><input type="checkbox" name="record[]" value="975" data-price="8.20"></span>
</div>
</section>
<section id="checkCost">
Total <input type="text" name="total" size="10" readonly="">
</section>
</section>
</form>

JavaScript text form validation from another field being updated by same form

I created below form: when you enter a name in first text box, it dynamically adds the names to another field below after pressing the + button. The function is implemented on the + button.
Now I want to add a validation logic within the same script, so that same name shouldn't be added twice. Please advise, only want to implement using javascript.
function promptAdd(list){
var text = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
text += inputs[i].value;
}
var li = document.createElement("li");
var node = document.createTextNode(text);
li.appendChild(node);
document.getElementById("list").appendChild(li);
}
<!doctype html>
<html>
<div class="row">
<div class="col-lg-6 mb-1">
<div class="card h-100 text-left">
<div class="card-body">
<h4 class="card-title">Add Resources</h4>
<input type="text" class="form-control" name="employee" placeholder="Enter Name" />
<small id="message" class="form-text text-muted">Press + to add to your list</small>
<button id="bd1" class="btn add-more" onclick="promptAdd(list)" type="button">+</button>
<br></br>
<h5>List of Resources added</h5>
<div class="form-control" id="list">
<span id="list">
</div>
</div>
</div>
</div>
</div>
</html>
The validation could be implemented simply by looping through all the li's and comparing the text of every li with the value of the input and if the values matches just return false, like :
var lis = document.querySelectorAll('#list li');
for (var i = 0; i < lis.length; i++) {
if (lis[i].innerText == text) {
return false;
}
}
Hope this helps.
function promptAdd(list) {
var text = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
text += inputs[i].value;
}
var lis = document.querySelectorAll('#list li');
for (var i = 0; i < lis.length; i++) {
if (lis[i].innerText == text ){
resetInputs();
return false;
}
}
var li = document.createElement("li");
var node = document.createTextNode(text);
li.appendChild(node);
document.getElementById("list").appendChild(li);
resetInputs();
}
function resetInputs(){
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
inputs[i].value = "";
}
}
<div class="row">
<div class="col-lg-6 mb-1">
<div class="card h-100 text-left">
<div class="card-body">
<h4 class="card-title">Add Resources</h4>
<input type="text" class="form-control" name="employee" placeholder="Enter Name" />
<small id="message" class="form-text text-muted">Press + to add to your list</small>
<button id="bd1" class="btn add-more" onclick="promptAdd(list)" type="button">+</button>
<br><br>
<h5>List of Resources added</h5>
<div class="form-control" id="list">
<span id="list"></span>
</div>
</div>
</div>
</div>
</div>
Loop though all li elements and check their innerText with the new text.
If you want to ignore capitalization you can use innerText.toUpperCase() === newText.toUpperCase()
function promptAdd(list) {
var text = "";
var inputs = document.querySelectorAll("input[type=text]");
for (var i = 0; i < inputs.length; i++) {
text += inputs[i].value;
}
if (textAlreadyExistsInList(text)) {
return;
};
var li = document.createElement("li");
var node = document.createTextNode(text);
li.appendChild(node);
document.getElementById("list").appendChild(li);
};
function textAlreadyExistsInList(text) {
var itemExists = false;
var items = document.getElementById("list").querySelectorAll('li');
for (var i = 0; i < items.length; i++) {
if (items[i].innerText === text) { //to ignore casing: items[i].innerText.toUpperCase() === text.toUpperCase()
itemExists = true;
break;
}
}
return itemExists;
}
<div class="row">
<div class="col-lg-6 mb-1">
<div class="card h-100 text-left">
<div class="card-body">
<h4 class="card-title">Add Resources</h4>
<input type="text" class="form-control" name="employee" placeholder="Enter Name" />
<small id="message" class="form-text text-muted">Press + to add to your list</small>
<button id="bd1" class="btn add-more" onclick="promptAdd(list)" type="button">+</button>
<br></br>
<h5>List of Resources added</h5>
<div class="form-control" id="list">
</div>
You need one input text so given that id is better . Here I set insert_name as id ! Get all li by querySelectAll and check text with innerHTML and input value .
function promptAdd(list){
var inputs = document.getElementById("insert_name").value;
if(checkDuplicate(inputs)) return; // check duplicate
var li = document.createElement("li");
var node = document.createTextNode(inputs);
li.appendChild(node);
document.getElementById("list").appendChild(li);
}
function checkDuplicate(name) {
var flag = false;
var lis = document.querySelectorAll("li");
for(var i = 0 ;i < lis.length;i++) {
if(name == lis[i].innerHTML) {
flag = true;
break;
}
}
return flag;
}

cash denomination calculator

I've created cash denomination calculator in jquery, and it's working fine once you add entry but suppose if you try to change those entries then it's not calculating values as i expected.
Just fill those values and you'll get total of all, but if try to change the value of input box inside div with '.mul_by' class[i.e. the small input box before '=' sign] then it's not calculating the total properly.
And here's the jsFiddle for the same.
$('.mul_by').each(function (i) {
var _this = $(this),
//set default input value to zero inside .mul-by div
setZero = _this.find('.form-control').val(0),
//set default input value to zero inside .mul-val div
setDenominationVal = _this.siblings('.mul_val').find('.form-control').val(0),
//set default input value to zero inside .total div
setTotalVal = $('.total').val(0);
setZero.on('change', function () {
//watch and store input val. inside .mul_by
var getUpdatedVal = _this.find('.form-control').val(),
//get label text
getDenominationVal = parseInt(_this.siblings('label').text()),
//update mul_by div after multiplication
updateDenominationVal = _this.siblings('.mul_val').find('.form-control');
if (getUpdatedVal > 0) {
var vals = updateDenominationVal.val(getUpdatedVal * getDenominationVal);
total = parseInt(setTotalVal.val()) + parseInt(vals.val());
setTotalVal.val(total);
} else {
updateDenominationVal.val(0);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-2 col-xs-2" for="batch">2000</label>
<div class="col-md-1 col-xs-4 mul_by">
<span>x </span> <input type="text" class="form-control">
</div>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2 col-xs-2" for="batch">500</label>
<div class="col-md-1 col-xs-4 mul_by">
<span>x </span> <input type="text" class="form-control">
</div>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2 col-xs-2" for="batch">100</label>
<div class="col-md-1 col-xs-4 mul_by">
<span>x </span> <input type="text" class="form-control">
</div>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<hr>
<label class="control-label col-md-2 col-xs-2" for="batch">total:</label>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control total">
</div>
</div>
</form>
How do i update total after making changes?
Hope you understand it. Thanks in advance for your help.
Please check this code i get proper result I had made lot of changes at end hope you will get desired result:-
$(document).ready(function () {
$('.mul_by').each(function (i) {
var _this = $(this),
//set default input value to zero inside .mul-by div
setZero = _this.find('.form-control').val(0),
//set default input value to zero inside .mul-val div
setDenominationVal = _this.siblings('.mul_val').find('.form-control').val(0);
//set default input value to zero inside .total div
setTotalVal = $('.total').val(0);
setZero.on('change', function () {
var getcurrentval = $(this).val();
console.log('getcurrentval',getcurrentval)
//watch and store input val. inside .mul_by
var getUpdatedVal = _this.find('.form-control').val(),
//get label text
getDenominationVal = parseInt(_this.siblings('label').text()),
//update mul_by div after multiplication
updateDenominationVal = _this.siblings('.mul_val').find('.form-control');
console.log(getUpdatedVal,getDenominationVal)
var vals = 0,total=0;
if(getUpdatedVal > 0){
if(updateDenominationVal.val()>0){
vals = updateDenominationVal.val(getUpdatedVal * getDenominationVal - updateDenominationVal.val());
total = parseInt(setTotalVal.val()) + parseInt(vals.val()) ;
updateDenominationVal.val(getUpdatedVal * getDenominationVal);
console.log('total',total,'setTotal',setTotalVal.val(),vals.val());
}
else{
vals = updateDenominationVal.val(getUpdatedVal * getDenominationVal);
updateDenominationVal.val(getUpdatedVal * getDenominationVal);
total = parseInt(setTotalVal.val()) + parseInt(vals.val());
}
console.log(vals.val());
setTotalVal.val(total);
} else{
updateDenominationVal.val(0);
}
});
});
});

Javascript percentage calculation for each form field

I'm trying to work out the percentage value for each field in a form. However my current code is only working out the value for the first field or whichever one is focused.
I'd like it so that the percentage value only for the filed in the same fieldset
The current code works but i'd like to apply to to multiple fieldsets without them interfering with other inputs on the same page
In the snippet you can see that the two separate amounts which are editing each others details
function percentageCal() {
var $price = $(".form-item--invamt .form-item__input").on("input", calculatePerc),
$percentage = $(".form-item__input-expand .percentage").on("input", calculatePrice),
$currency = $(".form-item__input-expand .currency").on("focus", removePercent),
$none = $(".form-item--charges .no-charge").on("focus", removePercent),
$increase = $(".wrapper-types__percentage-value"),
$increaseWrap = $(".wrapper-types__percentage");
$($percentage).add($currency).keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
return false;
}
});
function calculatePrice() {
var percentage = parseFloat($(this).val());
var price = parseFloat($price.val());
var calcPrice = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPrice;
$increase.text(newPrice);
$increaseWrap.fadeIn();
if (isNaN(newPrice)) {
$increaseWrap.hide();
}
}
function calculatePerc() {
var percentage = $percentage.val();
var price = parseFloat($(this).val());
var calcPerc = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPerc;
$increase.text(newPrice);
}
function removePercent() {
$increaseWrap.fadeOut();
}
}
percentageCal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="wrapper-types__investment">
<legend class="sr-only">Investment 1</legend>
<div class="form-item form-item--required form-item--invamt">
<label class="form-item__label" for="wrappers[0]">Investment amount</label>
<div class="form-item__input-labelled">
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[0]" id="wrappers[0]" min="0" value="15000" required>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="form-item__label">Charges</span>
<div class="form-item form-item--charges">
<label class="form-item__input-label-expand" for="percentage1">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage1">
</div>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
<div class="form-item form-item--action-btns">
</div>
</fieldset>
<fieldset class="wrapper-types__investment">
<legend class="sr-only">Investment 2</legend>
<div class="form-item form-item--required form-item--invamt">
<label class="form-item__label" for="wrappers[1]">Investment amount</label>
<div class="form-item__input-labelled">
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[1]" id="wrappers[1]" min="0" value="13005.02" required>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="form-item__label">Charges</span>
<div class="form-item form-item--charges">
<label class="form-item__input-label-expand" for="percentage2">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage2">
</div>
</div>
</div>
<div class="form-item form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
<div class="form-item form-item--action-btns">
</div>
</fieldset>
Instead of IDs, use classes and DOM traversal functions to find the fields in the same fieldset.
function percentageCal() {
var $price = $(".form-item--invamt .form-item__input").on("input", calculatePerc),
$percentage = $(".form-item__input-expand .percentage").on("input", calculatePrice),
$currency = $(".form-item__input-expand .currency").on("focus", removePercent),
$none = $(".form-item--charges .no-charge").on("focus", removePercent),
$increase = $(".wrapper-types__percentage-value"),
$increaseWrap = $(".wrapper-types__percentage");
$percentage.add($currency).keypress(function(event) {
if (event.which != 8 && event.which != 0 && (event.which < 48 || event.which > 57)) {
return false;
}
});
function calculatePrice() {
var $fieldset = $(this).closest("fieldset");
var percentage = parseFloat($(this).val());
var price = parseFloat($fieldset.find(".form-item--invamt .form-item__input").val());
var calcPrice = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPrice;
$fieldset.find(".wrapper-types__percentage-value").text(newPrice);
$fieldset.find(".wrapper-types__percentage").fadeIn();
if (isNaN(newPrice)) {
$fieldset.find(".wrapper-types__percentage").hide();
}
}
function calculatePerc() {
var $fieldset = $(this).closest("fieldset");
var percentage = $fieldset.find(".form-item__input-expand .percentage").val();
var price = parseFloat($(this).val());
var calcPerc = parseFloat((price * percentage / 100).toFixed(2));
var newPrice = price + calcPerc;
$fieldset.find(".wrapper-types__percentage-value").text(newPrice);
}
function removePercent() {
var $fieldset = $(this).closest("fieldset");
$fieldset.find(".wrapper-types__percentage").fadeOut();
}
}
percentageCal();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset class="wrapper-types__investment">
<div class="form-item--invamt">
<div>
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[0]" id="wrappers[0]" min="0" value="15000" required>
</div>
</div>
<div class="form-item--charges-wrap">
<div class="form-item--charges">
<label class="form-item__input-label-expand" for="percentage">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage">
</div>
</div>
</div>
<div class="form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
</fieldset>
<fieldset class="wrapper-types__investment">
<div class="form-item--invamt">
<div>
<span class="form-item__input-label">£</span>
<input class="form-item__input " type="number" name="wrappers[1]" id="wrappers[1]" min="0" value="15000" required>
</div>
</div>
<div class="form-item--charges-wrap">
<div class="form-item--charges">
<label class="form-item__input-label-expand" for="percentage1">%</label>
<div class="form-item__input-expand">
<input class="form-item__input percentage" type="number" name="percentage" id="percentage1">
</div>
</div>
</div>
<div class="form-item--charges-wrap">
<span class="wrapper-types__percentage">= £<span class="wrapper-types__percentage-value"></span></span>
</div>
</fieldset>

How to append auto-incremented number for label text

I am implementing an extend form function, in which there is a label text (marked in html) that I hope to include a number to increment.
So every time when a form is extended/cloned, the label text in the extended form shows Student 1, Student 2... accordingly. Can I be advised how to do that?
var counter = 0;
function moreFields(val1, val2, val3) {
counter++;
var newField = document.getElementById(val1).cloneNode(true);
newField.id = '';
newField.style.display = 'block';
var newFields = newField.querySelectorAll('[name], [id], [for]');
for (var i=0;i<newFields.length;i++) {
var theNames = newFields[i].name
if (theNames)
newFields[i].name = "data[" + val3 + "][" + counter + "][" + theNames + "]";
var theNames2 = newFields[i].id;
if (theNames2)
newFields[i].id = theNames2 + counter;
var theNames3 = newFields[i].htmlFor;
if (theNames3)
newFields[i].htmlFor = theNames3 + counter;
}
var insertHere = document.getElementById(val2);
insertHere.parentNode.insertBefore(newField,insertHere);
}
<span id="readroot" style="display: none">
<div class="row">
<div class="col-lg-3">
Grade 6
</div>
<div class="col-lg-3">
Male
</div>
<div class="col-lg-6">
<div class="row">
<div class="col-lg-12">
<!-- Student number needs to increase when a new form is extended. -->
<label>Student 1</label>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<label for="display_student_1_grade">Grade</label>
<div id="display_student_1_grade"></div>
</div>
<div class="col-lg-6">
<label for="display_student_1_gender">Gender</label>
<div id="display_student_1_gender"></div>
</div>
</div>
</div>
</div>
<input class="btn btn-default" type="button" value="Remove" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</span>
<span id="writeroot"></span>
<input class="btn btn-default" type="button" onclick="moreFields('readroot', 'writeroot', 'Student')" value="One More Student" />
To answer the question directly, you just need to find the appropriate <label> and update the innerHTML (see below).
However, what you are doing here can be achieved using the new HTML5 template element without having to hide <span> elements. Additionally, you have to remember that when you remove a student, the counter isn't going to decrease, nor are the already added students going to update. If you want that kind of functionality, you may want to look into a Javascript MVVM, like Angular.
var counter = 0;
function moreFields(val1, val2, val3) {
counter++;
var newField = document.getElementById(val1).cloneNode(true);
newField.id = '';
newField.style.display = 'block';
// Find the label here and update the innerHTML appropriately
newField.querySelector(".col-lg-12 label").innerHTML = "Student " + counter;
var newFields = newField.querySelectorAll('[name], [id], [for]');
for (var i=0;i<newFields.length;i++) {
var theNames = newFields[i].name
if (theNames)
newFields[i].name = "data[" + val3 + "][" + counter + "][" + theNames + "]";
var theNames2 = newFields[i].id;
if (theNames2)
newFields[i].id = theNames2 + counter;
var theNames3 = newFields[i].htmlFor;
if (theNames3)
newFields[i].htmlFor = theNames3 + counter;
}
var insertHere = document.getElementById(val2);
insertHere.parentNode.insertBefore(newField,insertHere);
}
<span id="readroot" style="display: none">
<div class="row">
<div class="col-lg-3">
Grade 6
</div>
<div class="col-lg-3">
Male
</div>
<div class="col-lg-6">
<div class="row">
<div class="col-lg-12">
<!-- Student number needs to increase when a new form is extended. -->
<label>Student 1</label>
</div>
</div>
<div class="row">
<div class="col-lg-6">
<label for="display_student_1_grade">Grade</label>
<div id="display_student_1_grade"></div>
</div>
<div class="col-lg-6">
<label for="display_student_1_gender">Gender</label>
<div id="display_student_1_gender"></div>
</div>
</div>
</div>
</div>
<input class="btn btn-default" type="button" value="Remove" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" />
</span>
<span id="writeroot"></span>
<input class="btn btn-default" type="button" onclick="moreFields('readroot', 'writeroot', 'Student')" value="One More Student" />

Categories

Resources