javascript/jquery config generator - javascript

in jsfiddle im trying to make a configuration generator for an app i have, basically the format is as follows:
type;user;pass;ip:port
with ip:port being optional
it would be generated from a selectbox two textboxes, where its inputted as user:pass and in the other ip:port, if you don't understand, this is a little visual ive made:
pic of what i want

For what it's worth:
document.querySelector('button').addEventListener('click', function() {
var type = document.getElementById('type').value;
var useipport = document.getElementById('useipport').checked;
var userpass = document.getElementById('userpass').value;
var ipport = document.getElementById('ipport').value;
var output = document.getElementById('output');
var users = [],
ips = [],
config = [];
if (userpass.length > 0) users = userpass.split('\n');
if (ipport.length > 0) ips = ipport.split('\n');
var ix = 0;
while (ix < users.length || ix < ips.length) {
var user = '';
user += type + ';';
if (users[ix]) user += users[ix] + ';';
if (useipport && ips[ix]) user += ips[ix];
config.push(user);
ix++;
}
output.value = config.join("\n");
});
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet"/>
<div class="container">
<div class="row">
<div class="six columns">
<select id="type">
<option value="PT">PT</option>
<option value="GL">GL</option>
</select>Type
</div>
<div class="six columns">
<label>
<input type="checkbox" id="useipport">
<span class="label-body">Use IP/Port</span>
</label>
</div>
</div>
<div class="row">
<div class="six columns">
<textarea class="u-full-width" placeholder="abc:123" id="userpass"></textarea>
</div>
<div class="six columns">
<textarea class="u-full-width" placeholder="1.1.1.1:1111" id="ipport"></textarea>
</div>
</div>
<div class="row">
<div class="six columns">
<textarea class="u-full-width" id="output"></textarea>
</div>
<div class="six columns">
<button>Create</button>
</div>
</div>
</div>

Related

How make select option value start over everytime changing its value?

i've been making 2 select option box. Which is worked, the first one is ranged between 2010-2019. The second one, i wanted it to start from the value of the first select option box with its range +10 years.
Yes it did worked! But the problem is, if i did my first choose it worked. Then when i change the first option box value, it gave me another loop.
For example :
First option box i choose : 2011
Second option box value will be : 2011, 2012, 2013, 2014, .. ,2021.
Then i click the first option box to be : 2012
Second option box value will be : 2011,2012, 2013,2014,..,2021, 2012, 2013, 2014, 2015, .., 2022.
Here's the code i've been made.
<script>
/* NILAI TAHUN BERLAKU SAMPAI BERDASAR TAHUN BERLAKU MULAI */
$("#idTahunBerlaku").change(
function() {
var startkiri = parseInt($(this).val());
var start = startkiri;
var end = startkiri + 10;
var options = "";
for (var year = start; year <= end; year++) {
options += "<option>" + year + "</option>";
}
document.getElementById("idTahunBerlakuS")
.insertAdjacentHTML("beforeend", options);
});
var start = 2010;
var end = 2019;
var options = "";
for (var year = start; year <= end; year++) {
options += "<option>" + year + "</option>";
}
document.getElementById("idTahunBerlaku").insertAdjacentHTML(
"beforeend", options);
var start = 1;
var end = 12;
var options = "";
for (var month = start; month <= end; month++) {
options += "<option>" + month + "</option>";
}
document.getElementById("idBulanBerlaku").insertAdjacentHTML(
"beforeend", options);
var startkiri = $('#idTahunBerlaku :selected').val();
var start = 1;
var end = 12;
var options = "";
for (var month = start; month <= end; month++) {
options += "<option>" + month + "</option>";
}
document.getElementById("idBulanBerlakuS").insertAdjacentHTML(
"beforeend", options);
$('#idBtnSimpanSimpan')
.click(
function() {
if ($('#idPenerbit').val().trim() == ""
|| $('#idtrainingName').val().trim() == "") {
alert("ISI SEMUA FORM TERLEBIH DAHULU");
} else {
if ($('#idTahunBerlaku').val() > $(
'#idTahunBerlakuS').val()) {
alert("TAHUN BERLAKU MULAI TIDAK BOLEH LEBIH KECIL DARI BERLAKU SAMPAI");
} else {
debugger;
$("input, textarea").each(function(){
$(this).val(jQuery.trim($(this).val()));
});
var vDatasertifikasi = $(
'#idFrmAddSertifikasi').serialize();
alert(vDatasertifikasi);
debugger;
$
.ajax({
url : '/savesertifikasi',
type : 'POST',
data : vDatasertifikasi,
dataType : "json",
success : function(model) {
debugger;
if (model.status == "berhasil") {
alert("Data berhasil disimpan");
$(
'#idMdlNewSertifikasi')
.modal('hide');
window.location = './sertifikasi'
debugger;
} else {
alert("Data salah");
}
},
error : function(model) {
debugger;
}
});
}
}
});
// DISABLE PILIHAN
$(".clSelectKiri").change(function() {
if ($('#idTahunBerlaku').val() && $('#idBulanBerlaku').val()) {
$(".clTgglKanan").removeAttr("disabled");
} else {
$(".clTgglKanan").attr("disabled", "disabled");
}
}).trigger("change");
</script>
<form class="form-horizontal" id="idFrmAddSertifikasi" method="post">
<div class="row">
<div class="col-sm-12">
<div class="row">
<!-- LEVEL 1 / KIRI -->
<div class="col-xs-8 col-sm-6">
<div class="col-xs-12">
<label for="SertifikasiName" class="control-label">Nama
Sertifikasi<sup>*</sup>
</label>
<div class="form-group">
<div class="col-sm-12">
<input type="text" class="form-control clborderbiru"
maxlength="50" id="idtrainingName" name="certificate_name"
placeholder="" title="MAKS. KARAKTER 50">
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<label for="schoolName" class="control-label">Berlaku
Mulai</label>
<div class="row">
<div class="col-xs-8 col-sm-6">
<div class="form-group">
<div class="col-sm-12">
<select class="form-control clborderbiru clSelectKiri"
id="idBulanBerlaku" name="valid_start_month">
<option value="0" disabled selected hidden>- Pilih
Bulan -</option>
</select>
</div>
</div>
</div>
<div class="col-xs-4 col-sm-6">
<div class="form-group">
<div class="col-sm-12">
<select class="form-control clborderbiru clSelectKiri"
id="idTahunBerlaku" name="valid_start_year">
<option value="0" disabled selected hidden>- Pilih
Tahun -</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- LEVEL 2 / KANAN -->
<div class="col-xs-4 col-sm-6">
<div class="col-xs-12">
<label for="organizer" class="control-label">Penerbit<sup>*</sup></label>
<div class="form-group">
<div class="col-sm-12">
<input type="text" class="form-control clborderbiru"
id="idPenerbit" name="publisher" placeholder="">
</div>
</div>
</div>
<div class="col-xs-12 col-sm-12">
<label for="schoolName" class="control-label">Berlaku
Sampai</label>
<div class="row">
<div class="col-xs-8 col-sm-6">
<div class="form-group">
<div class="col-sm-12">
<select class="form-control clTgglKanan clborderbiru"
id="idBulanBerlakuS" name="until_month">
<option value="" disabled selected hidden>- Pilih
Bulan -</option>
</select>
</div>
</div>
</div>
<div class="col-xs-4 col-sm-6">
<div class="form-group">
<div class="col-sm-12">
<select class="form-control clTgglKanan clborderbiru"
id="idTahunBerlakuS" name="until_year">
<option value="" disabled selected hidden>- Pilih
Tahun -</option>
</select>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="col-xs-12">
<label for="notes" class="control-label">Catatan</label>
<div class="form-group">
<div class="col-sm-12">
<textarea class="form-control clborderbiru" id="idCatatan"
rows="6" name="notes"></textarea>
</div>
</div>
</div>
<div class="col-md-offset-10">
<div class="btn-group">
<button type="button" class="btn clBtnMdl" data-dismiss="modal">Batal</button>
<button type="button" class="btn clBtnMdl" id="idBtnSimpanSimpan">Simpan</button>
</div>
</div>
</div>
</div>
</form>
you have to clear the content of the select before modifying data.
insertAdjacentHTML simply inserts into the DOM at specified location. So you have to clear existing elements before adding your modifications.
$("#idTahunBerlaku").change(
function() {
var startkiri = parseInt($(this).val());
var start = startkiri;
var end = startkiri + 10;
var options = "";
for (var year = start; year <= end; year++) {
options += "<option>" + year + "</option>";
}
//Empties existing options.
$("#idTahunBerlakuS").empty();
//Appends '- Pilih Bulan -'. You can ignore this if you don't need it.
$('#idTahunBerlakuS').append($("<option></option>").attr("value",'').text('- Pilih Bulan -'));
document.getElementById("idTahunBerlakuS").insertAdjacentHTML("beforeend", options);
});
Hope this helps
Ok so from the comment i've said before, i just added a little thing inside of my loop without changing anything. Which is works and it didn't make my "placeholder" to be an option.
$("#idTahunBerlaku").change(
function() {
var startkiri = parseInt($(this).val());
var start = startkiri;
var end = startkiri + 10;
var options = "";
for (var year = start; year <= end; year++) {
options += "<option>" + year + "</option>";
$("#idTahunBerlakuS").empty();
}
document.getElementById("idTahunBerlakuS")
.insertAdjacentHTML("beforeend", options);
});

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>

Angular Binding not working with a Select Box in HTML

I have prepared a simple template that displays a select box with options.
The template
<div class="jumbotron" style="background-color:white">
</div>
<div class="jumbotron container-fluid">
<h3 align="center">PAN Bulk Upload</h3>
</div>
<div class="container">
<div class="row">
<div class="col-lg-9">
<div style="border-right:1px solid #cbc6c6">
<div class="container panel-body">
<label class="custom-file-upload">
<input id="fileChoose" type="file" custom-on-change="uploadFile" />
<i class="fa fa-cloud-upload"> Choose Device Group File</i>
</label>
<hr/>
<select size=5 style="width:200px;height:100px" ng-options="o as o for o in deviceGroups">
</select>
</div>
<div class="container">
<button ng-click="validateDeviceGroups()">Validate</button>
<button ng-click="commitDeviceGroups()">Commit</button>
</div>
</div>
</div>
<div class="col-lg-3">
<textarea rows="20" cols="35"></textarea>
</div>
</div>
</div>
The Angular Controller
angapp.controller('panbulkCtrl', function($scope) {
$scope.deviceGroups = ["Hi","Hello"];
$scope.uploadFile = function() {
var filename = event.target.files[0].name;
var reader = new FileReader();
reader.onload = function (e) {
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var cells = rows[i].split(",");
for (var j = 0; j < cells.length; j++) {
console.log(cells[i]);
$scope.deviceGroups.push(cells[i]);
}
}
}
reader.readAsText(event.target.files[0]);
};
$scope.validateDeviceGroups = function(){
}
});
The added strings in deviceGroups do not appear in the Select box as options. What is wrong?
As per select | AngularJS docs, ngModel is required argument.
Pass that like ng-model="selected" or something and it would work!
<select size=5 style="width:200px;height:100px" ng-model="selected"
ng-options="o as o for o in deviceGroups">
</select>
Here's working example
Please refer this. May help you try to make ng-options simpler and add ng-model for same -
var myApp = angular.module("myApp",[]);
myApp.controller("myCntr",function($scope){
$scope.deviceGroups = ["hi","hello"];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCntr">
<select multiple size=5 style="width:200px;height:100px" ng-options="o for o in deviceGroups" ng-model="selected"/>
</div>
Try this one
ng-model="deviceGroups[0]"

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