Switching between div elements using Javascript - javascript

My website has 3 services, I want to be able to click on service 1 and see menu 1, click on service 2 and see menu 2, click on service 3 and see menu 3. I have the following code but it is not working as expected. When I click on service 2 and service 3, nothing shows up.
HTML :
<div class="row" id="menu_service1">
<div class="col-md-4">
<span><h5>Choose a line</h5> <select id="lines" class="form-control"></select></span>
<span><h5>Choose a stop</h5> <select id="stop" class="form-control"></select></span>
</div>
</div>
<div class="row" id="menu_service2">
<div class="col-md-4">
<span><h5>Choose a stop</h5> <select id="stop" class="form-control"></select></span>
<span><h5>Choose a stop</h5> <select id="stop" class="form-control"></select></span>
</div>
</div>
<div class="row" id="menu_service3">
<div class="col-md-4">
<p>blah</p>
</div>
</div>
JS :
$(document).ready(function() {
var line_array = ["Line 1", "Line 2", "Line 3"];
var stops = ["stop1", "stop2", "stop3"] ;
for (var i = 0; i < line_array.length; i++) {
$('#lines').append('<option>' + line_array[i] + '</option>');
}
for (var i = 0; i < stops.length; i++) {
$('#stop').append('<option>' + stops[i] + '</option>');
}
$('#menu_service1').hide();
$('#menu_service2').hide();
$('#menu_service3').hide();
$('#Service_1').click(function() {
$('#menu_service1').toggle();
});
$('#Service_2').click(function() {
$('#menu_service2').toggle();
});
$('#Service_3').click(function() {
$('#menu_service3').toggle();
});
});

Working Fiddle.
id should be unique in same document, so try to replace the duplicated ones by general classes, e.g:
<span><h5>Choose a line</h5> <select class="form-control lines"></select></span>
<span><h5>Choose a stop</h5> <select class="form-control stop"></select></span>
And in your JS use them with class selector dot ., like :
$('.lines').append('<option>' + line_array[i] + '</option>');
You should also fix the typos in the following two lines by adding id selector sogn # :
$('menu_service2').toggle();
$('menu_service2').toggle();
Should be :
$('#menu_service2').toggle();
$('#menu_service2').toggle();
Also you could use comma , separator for multiple selectors, so instead of :
$('#menu_service1').hide();
$('#menu_service2').hide();
$('#menu_service3').hide();
Use just :
$('#menu_service1,#menu_service2,#menu_service3').hide();
Hope this helps.
$(document).ready(function() {
var line_array = ["Line 1", "Line 2", "Line 3"];
var stops = ["stop1", "stop2", "stop3"] ;
for (var i = 0; i < line_array.length; i++) {
$('.lines').append('<option>' + line_array[i] + '</option>');
}
for (var i = 0; i < stops.length; i++) {
$('.stop').append('<option>' + stops[i] + '</option>');
}
$('#menu_service1,#menu_service2,#menu_service3').hide();
$('#Service_1').click(function() {
$('.row').hide();
$('#menu_service1').toggle();
});
$('#Service_2').click(function() {
$('.row').hide();
$('#menu_service2').toggle();
});
$('#Service_3').click(function() {
$('.row').hide();
$('#menu_service3').toggle();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<button id='Service_1'>Service 1</button>
<button id='Service_2'>Service 2</button>
<button id='Service_3'>Service 3</button>
<div class="row" id="menu_service1">
<div class="col-md-4">
<span><h5>Choose a line1</h5> <select class="form-control lines"></select></span>
<span><h5>Choose a stop1</h5> <select class="form-control stop"></select></span>
</div>
</div>
<div class="row" id="menu_service2">
<div class="col-md-4">
<span><h5>Choose a line2</h5> <select class="form-control lines"></select></span>
<span><h5>Choose a stop2</h5> <select class="form-control stop"></select></span>
</div>
</div>
<div class="row" id="menu_service3">
<div class="col-md-4">
<p>blah</p>
</div>
</div>

You forgot the # sign in front of the id's in your selectors.
$('#menu_service2').toggle();
$('#menu_service3').toggle();

I prefer to write less lines of code to obtain the same result.
$(function () {
var line_array = ["Line 1", "Line 2", "Line 3"];
var stops = ["stop1", "stop2", "stop3"] ;
for (var i = 0; i < line_array.length; i++) {
$('[id^=lines]').append('<option>' + line_array[i] + '</option>');
}
for (var i = 0; i < stops.length; i++) {
$('[id^=stop]').append('<option>' + stops[i] + '</option>');
}
$('[id^=menu_service]').hide();
$('[id^=Service_]').click(function() {
var currDiv = this.getAttribute('data-div');
$('div.row:not(#' + currDiv + ')').hide();
$('#' + currDiv).toggle();
});
});
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<button id='Service_1' data-div="menu_service1">Service 1</button>
<button id='Service_2' data-div="menu_service2">Service 2</button>
<button id='Service_3' data-div="menu_service3">Service 3</button>
<div class="row" id="menu_service1">
<div class="col-md-4">
<span><h5>Choose a line</h5> <select id="lines1" class="form-control"></select></span>
<span><h5>Choose a stop</h5> <select id="stop1" class="form-control"></select></span>
</div>
</div>
<div class="row" id="menu_service2">
<div class="col-md-4">
<span><h5>Choose a stop</h5> <select id="stop2" class="form-control"></select></span>
<span><h5>Choose a stop</h5> <select id="stop2" class="form-control"></select></span>
</div>
</div>
<div class="row" id="menu_service3">
<div class="col-md-4">
<p>blah</p>
</div>
</div>

Related

Dynamically add rows to an invoice-form with JQuery

I have a formfield with a static row for an invoice position. With + and - buttons I can add or remove additional rows for invoice positions dynamically. This works fine, but within each row I have a have a selectbox that switches the calculation method for the row (from km- to hour- or misc-based). This last feature only works for the first static row, not for the added rows?
HTML
<form action="" method="post">
<div class="mb-3">
<div id="position_0" class="row align-items-start">
<div class="col-4">
<label for="description" class="form-label">Beschreibung</label>
<textarea class="form-control" id="description_0" name="description_0" rows="1"></textarea>
</div>
<div class="col-2">
<label for="date" class="form-label">Tag der Leistung</label>
<input type="text" class="form-control" id="date_0" name="date_0">
</div>
<div class="col-1">
<label for="amount" class="form-label">Menge</label>
<input type="text" class="form-control" id="amount_0" name="amount_0">
</div>
<div class="col-2">
<label for="type" class="form-label">Abrechnungsform</label>
<select class="form-select" id="type_0" name="type_0">
<option value="km" selected>Kilometer</option>
<option value="hours">Stunden</option>
<option value="misc">Sonstiges</option>
</select>
</div>
<div class="col-1">
<label for="price" class="form-label">Einzelpreis</label>
<input type="text" class="form-control" id="price_0" name="price_0" value="{{price_km}}">
</div>
<div class="col-2">
<label for="sum" class="form-label">Summe</label>
<input type="text" class="form-control" id="sum_0" name="sum_0">
</div>
</div>
</div>
<div id="multiple"></div>
<button type="submit" class="btn btn-primary float-start">Speichern</button>
</form>
<button class="btn btn-primary float-end" onclick="addItems()"><i class="bi bi-plus"></i></button>
<button class="btn btn-primary float-end" onclick="removeItems()"><i class="bi bi-dash"></i></button>
Javascript/JQuery
<script>
var formatter = new Intl.NumberFormat('de-DE', {
style: 'currency',
currency: 'EUR',
});
var km = 0.97;
var hours = 12;
var misc = 0;
// THIS DOES NOT WORK START
$("#multiple").each(function () {
var n = $(this).find("div.mb-3").length;
$('#type_' + n).on('change', function () {
if (this.value === 'km') {
$('#price_' + n).val(formatter.format(km));
} else if (this.value === 'hours') {
$('#price_' + n).val(formatter.format(hours));
} else if (this.value === 'misc') {
$('#price_' + n).val(formatter.format(misc));
}
});
});
// THIS DOES NOT WORK END
function addItems() {
$("#multiple").each(function () {
var i = $(this).find("div.col").length;
var n = (i / 6) + 1;
$(this).append(`<div class="mb-3">
<div id="position_` + n + `" class="row align-items-start">
<div class="col col-4">
<textarea class="form-control" id="description_` + n + `" name="description_` + n + `" rows="1"></textarea>
</div>
<div class="col col-2">
<input type="text" class="form-control" id="date_` + n + `" name="date_` + n + `">
</div>
<div class="col col-1">
<input type="text" class="form-control" id="amount_` + n + `" name="amount_` + n + `">
</div>
<div class="col col-2">
<select class="form-select" id="type_` + n + `" name="type_` + n + `">
<option value="km" selected>Kilometer</option>
<option value="hours">Stunden</option>
<option value="misc">Sonstiges</option>
</select>
</div>
<div class="col col-1">
<input type="text" class="form-control" id="price_` + n + `" name="price_` + n + `" value="{{price_km}}">
</div>
<div class="col col-2">
<input type="text" class="form-control" id="sum_` + n + `" name="sum_` + n + `">
</div>
</div>
</div>`);
});
}
function removeItems() {
$("#multiple").each(function () {
var n = $(this).find("div.mb-3").length;
if (n != 0) {
$("#position_" + n).parents("div.mb-3").remove();
}
});
}
</script>
Only the initial items are "wired" the change event because you run
// this line loops only on the initial items
$("#multiple").each(function () {
To solve this you have to set an .on(event) function
// this is NOT a complete example
// 1. add a generic class to all the selects
<select class="form-select mytypeselect" id="type_0" name="type_0">
<option value="km" selected>Kilometer</option>
<option value="hours">Stunden</option>
<option value="misc">Sonstiges</option>
</select>
// 2. Set the on event, but all thing relative to the element (not fixed to the index or id
$('.mytypeselect').on('change', function () {
var self = $(this);
var row = self.closest(".row"); // find the row the select belongs at
if (self.val() === 'km') {
// find the input inside the row to change
row.find('.mypriceinput').val(formatter.format(km));
This is not optimal, but it solves my problem
// First row of the invoice
$('select#type_0').on('change', function () {
if ($(this).val() === 'km') {
$(this).parents('div').find('#price_0').val(formatter.format(km));
} else if ($(this).val() === 'hours') {
$(this).parents('div').find('#price_0').val(formatter.format(hours));
} else if ($(this).val() === 'misc') {
$(this).parents('div').find('#price_0').val(formatter.format(misc));
}
});
// Everytime the DOM changes
$("#multiple").bind("DOMSubtreeModified", function () {
$('.mytypeselect').on('change', function () {
var sibling = $(this).parents('div');
var n = (($(this).attr('id')).split('_'))[1];
if ($(this).val() === 'km') {
sibling.find('#price_' + n).val(formatter.format(km));
} else if ($(this).val() === 'hours') {
sibling.find('#price_' + n).val(formatter.format(hours));
} else if ($(this).val() === 'misc') {
sibling.find('#price_' + n).val(formatter.format(misc));
}
});
});

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);
});

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 add all the values of dynamically created Textbox

I am working on Billing System, where i have a dropdown which consist of lot of items and a textbox in front of it, which is a price of that item.
I am calling new dropdown and textbox each time using add button.
var i = 1;
var j = 11;
$(".btnAdd").click(function() {
i += 1;
j += 1;
$('#myDiv').after('<div class="row"><div class="col"><select id="' + i + '" style="width: 130px"><option value="val1">a</option><option value="val2">b</option><option value="val3">c</option><option value="valn">z</option></select><input type="text" id="' + j + '" /> </div></div>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv" class="row">
<div class="col">
<select id=" 1 " style='width: 130px'>
<option value='val1'>a</option>
<option value='val2'>b</option>
<option value='val3'>c</option>
<option value='valn'>z</option>
</select>
<input type="text" id=" 11 " name="txt" />
</div>
</div>
<button class="btnAdd">Add</button>
<div>
<input type="text" id=" totval " name="txt" />
<button class="Submit">Total</button>
</div>
My question is how to add all the values when the TOTAL button is clicked and store in TOTAL textbox ? Please help me in this ..
CHECK THIS FIDDLE -> https://fiddle.jshell.net/e20hc1wo/2/
Try this Fiddle
var i = 1;
var j = 11;
$(".btnAdd").click(function() {
i += 1;
j += 1;
$('#myDiv').after('<div class="row"><div class="col"><select id="' + i + '" style="width: 130px"><option value="val1">a</option><option value="val2">b</option><option value="val3">c</option><option value="valn">z</option></select><input type="text" id="' + j + '" /> </div></div>');
});
$('.Submit').on('click', function() {
var total = 0;
$('input[type=text]').not('#totval').each(function(index, item) {
total += parseInt($(item).val());
});
$('#totval').val(total);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="myDiv" class="row">
<div class="col">
<select id=" 1 " style='width: 130px'>
<option value='val1'>a</option>
<option value='val2'>b</option>
<option value='val3'>c</option>
<option value='valn'>z</option>
</select>
<input type="text" id=" 11 " name="txt" />
</div>
</div>
<button class="btnAdd">Add</button>
<div>
<input type="text" id="totval" name="txt" />
<button class="Submit">Total</button>
</div>
Implementing the sum is possible:
$(".Submit").click(function () {
var total = 0;
$("input:not(#totval)").each(function (_, e) {
total += parseInt(e.value, 10)
});
$("#totval").val(total);
});
Fiddle: https://fiddle.jshell.net/e20hc1wo/12/
But I think the code can be improved a lot if you add meaningful classes to these inputs created.
Improved: The following implementation uses a template row to avoid concatenating HTML code in JS.
<div class="row template">
<div class="col">
<select class="typeSelect" style='width: 130px'>
<option value='val1'>a</option>
<option value='val2'>b</option>
<option value='val3'>c</option>
<option value='valn'>z</option>
</select>
<input type="text" class="numberInput" />
</div>
</div>
<button class="btnAdd">Add</button>
<div>
<input type="text" id="totval" name="txt" />
<button class="Submit">Total</button>
</div>
JS:
var template = $(".template").remove();
$(".btnAdd").click(function () {
template.clone(true).insertBefore('.btnAdd');
}).click();
$(".Submit").click(function () {
var total = 0;
$(".numberInput").each(function (_, e) {
total += parseInt(e.value, 10)
});
$("#totval").val(total);
});
It is much shorter and cleaner
Fiddle: https://fiddle.jshell.net/e20hc1wo/23/
Add id to button
<button class= "Submit" id="btnTotal">Total</button>
Add function to javascript
$("#btnTotal").click(function () {
var total = 0;
$(".row input").each(function(){
total += parseInt($(this).val(),10);
})
$('#totval').val(total);
});

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