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);
});
Related
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));
}
});
});
I am new to web designing, i want to add show more button in drop down list. But i am getting data dynamically from database.
var $selectdropdrown = $('#dropdrown');
$.getJSON('/listofData', function(data1) {
$selectdropdrown.html('');
$selectdropdrown.append('<option>' + "--Select--" + '</option>');
$.each(data1.data, function(key, val) {
$selectdropdrown.append('<option id=' + val.id + '>' + val.name + '</option>');
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="col-sm-5 control-label">Select Area Name <span class="mandatory"></span></label>
<div class="col-sm-7">
<select class="form-control" id="dropdrown" name="dropdrown"></select>
</div>
</div>
In drop down i want to show first 10 records next records will show after show more button click.
change
<select class="form-control" id="dropdrown" name="dropdrown"></select>
to
<select class="form-control" id="dropdrown" name="dropdrown">
<option value="0">Show more</option>
</select>
Hope this will resolve u r issue
Thank you
try this code, it worked for me:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body >
<div class="form-group">
<label class="col-sm-5 control-label">Select Area Name <span class="mandatory"></span></label>
<div id="thisID" class="col-sm-7">
<select class="form-control" id="dropdrown" name="dropdrown"></select><br><br>
</div>
</div>
<script>
$('#thisID').ready(function(){
$.getJSON('listofData.json', function(result){
var counter = 0;
var input = $('<input id="more" type="button" value="For More detelis" style="display : none"><br><Br>');
$("#thisID").append(input);
var select = $('<select class="form-control" id="dropdrown2" name="dropdrown" style="display : none"></select>');
$("#thisID").append(select);
$.each(result, function(i, field){
localStorage.setItem('length', result.length);
if(counter<10 && counter< result.length){
$("#dropdrown").append('<option id='+field.id+'>'+field.name+'</option>');
counter++
}
else
$("#dropdrown2").append('<option id='+field.id+'>'+field.name+'</option>');
});
if( localStorage.getItem('length') > 10 ) {
input.show();
}
input.click(function()
{
select.show()
});
});
});
</script>
</body>
</html>
Hope I helped
iam working on form validation, my requirement is show erro message if user did not fill all field in a row. in my page there are two rows every row contains two input fields. when i click submit button when all fields are empty it should show error. page first two inputs working. when user enter first field the next field also mandatory. no need of second row, if user filled first row and also filed second row first field, the second row second field mandatory.
in this manner is my requirement i have written some code.
Thanks in advance.
HTML
function crtNewRelease() {
var versionIpa = document.getElementById("versionIpa");
var version1Error = document.getElementById("version1Error");
var selectDevice1 = document.getElementById("selectDevice1");
var selectDevice1Error = document.getElementById("selectDevice1Error");
var versionApk = document.getElementById("versionApk");
var version2Error = document.getElementById("version2Error");
var selectDevice2 = document.getElementById("selectDevice2");
var selectDevice2Error = document.getElementById("selectDevice2Error");
if (sltProject.value == "") {
sltProject.style.border = "solid 1px red";
firstNError.textContent = "Select Project";
firstNError.style.color = "red";
firstNError.style.marginTop = "10px"
sltProject.focus();
return false;
}
if (releaseName.value == "") {
releaseName.style.border = "solid 1px red";
lastNError.textContent = "Enter Release Name";
lastNError.style.color = "red";
lastNError.style.marginTop = "10px"
releaseName.focus();
return false;
}
var sameCls = document.getElementsByClassName("newformInputs");
var inputArray = [];
var result;
var i = 1
for (i = 1; i < sameCls.length; i++) {
result += sameCls[i]
if (result == 1) {
version1Error.textContent = "Enter version";
return false;
} else {
version1Error.style.display = "none";
}
}
}
<form name="createNewRelease" onsubmit="return crtNewRelease();">
<select class="form-control" id="sltProject">
<option value="">Select Project</option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">Domino’s Makeline App</option>
</select>
<div id="firstNError" class="firstN"></div>
<input class="form-control " placeholder="Release Name" type="text" id="releaseName">
<div id="lastNError" class="firstN"></div>
<div class="selectPlatform">
<h6>Select platforms (you can select both)</h6>
<div class="row">
<div class="col-md-5">
<input class="form-control newformInputs" placeholder="Version number" type="text" id="versionIpa" />
<div id="version1Error" class="firstN"></div>
</div>
<div class="col-md-5 ">
<select class="form-control newformInputs" id="selectDevice1">
<option value="">Select device</option>
<option>iPhone</option>
<option>iPad</option>
</select>
<div id="selectDevice1Error" class="selectDevice1Cls"></div>
</div>
<div class="col-md-1"> <span> </span></div>
</div>
<div class="row">
<div class="col-md-5 ">
<input class="form-control newformInputs" placeholder="Version number" type="text" id="versionApk">
<div id="version2Error" class="firstN"></div>
</div>
<div class="col-md-5 ">
<select class="form-control newformInputs" id="selectDevice2">
<option value="">Select device</option>
<option>iPhone</option>
<option>iPad</option>
</select>
<div id="selectDevice2Error" class="selectDevice2Cls"></div>
</div>
<div class="col-md-1"> <span></span></div>
</div>
</div>
<div class="btnsRow">
<button class="btn" type="submit">Create Release</button>
Cancel
</div>
</form>
OK i add it to this code.check it!.
<form name="createNewRelease" onsubmit="return crtNewRelease();">
<select class="form-control" id="sltProject">
<option value="">Select Project</option>
<option value="one">one</option>
<option value="two">two</option>
<option value="three">Domino’s Makeline App</option>
</select>
<div id="firstNError" class="firstN"></div>
<input class="form-control " placeholder="Release Name" type="text" id="releaseName">
<div id="lastNError" class="firstN"></div>
<div class="selectPlatform">
<h6>Select platforms (you can select both)</h6>
<div class="row">
<div class="col-md-5">
<input class="form-control newformInputs" placeholder="Version number" type="text" id="versionIpa" />
<div class="error"></div>
</div>
<div class="col-md-5 ">
<select class="form-control newformInputs" id="selectDevice1">
<option value="">Select device</option>
<option>iPhone</option>
<option>iPad</option>
</select>
<div class="error"></div>
</div>
<div class="col-md-1"> <span> </span></div>
</div>
<div class="row">
<div class="col-md-5 ">
<input class="form-control newformInputs" placeholder="Version number" type="text" id="versionApk">
<div class="error"></div>
</div>
<div class="col-md-5 ">
<select class="form-control newformInputs" id="selectDevice2">
<option value="">Select device</option>
<option>iPhone</option>
<option>iPad</option>
</select>
<div class="error"></div>
</div>
<div class="col-md-1"> <span></span></div>
</div>
</div>
<div class="btnsRow">
<button class="btn" type="submit">Create Release</button>
Cancel
</div>
</form>
JS :
function crtNewRelease() {
var versionIpa = document.getElementById("versionIpa");
var version1Error = document.getElementById("version1Error");
var selectDevice1 = document.getElementById("selectDevice1");
var selectDevice1Error = document.getElementById("selectDevice1Error");
var versionApk = document.getElementById("versionApk");
var version2Error = document.getElementById("version2Error");
var selectDevice2 = document.getElementById("selectDevice2");
var selectDevice2Error = document.getElementById("selectDevice2Error");
if (sltProject.value == "") {
sltProject.style.border = "solid 1px red";
firstNError.textContent = "Select Project";
firstNError.style.color = "red";
firstNError.style.marginTop = "10px"
sltProject.focus();
return false;
}
if (releaseName.value == "") {
releaseName.style.border = "solid 1px red";
lastNError.textContent = "Enter Release Name";
lastNError.style.color = "red";
lastNError.style.marginTop = "10px"
releaseName.focus();
return false;
}
var sameCls = document.getElementsByClassName("newformInputs");
var inputArray = [];
var errorPos = [];
var result;
var i = 0;
for (i = 0; i < sameCls.length; i++) {
result = sameCls[i];
if (result.value == "" ) {
errorPos.push(i);
} else {
//version1Error.style.display = "none";
}
}
//reset error class
var listerror = document.getElementsByClassName("error");
for(var t5 = 0 ; t5 < listerror.length ; t5++ ){
listerror[t5].textContent = "";
}
console.log(errorPos);
var flag = false;
if(errorPos.length > 0){
for (i = 0; i < sameCls.length; i=i+2 ) {
if(i % 2 == 0){
console.log(errorPos.indexOf(i));
if(errorPos.indexOf(i)==-1){
if(errorPos.indexOf(i+1)==-1){
flag = true;
}
else{
flag = false;
}
}
}
}
if(!flag){
for(var t2= 0 ; t2 < errorPos.length ; t2++){
console.log(sameCls[errorPos[t2]]);
for(var t3 = 0 ; t3 < sameCls[errorPos[t2]].parentNode.childNodes.length; t3++ ){
if(sameCls[errorPos[t2]].parentNode.childNodes[t3].className == "error"){
sameCls[errorPos[t2]].parentNode.childNodes[t3].textContent = "Erorr!!";
sameCls[errorPos[t2]].parentNode.childNodes[t3].style.display = "block";
return false;
}
}
}
}
}
return false;
}
Check It!
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>
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);
});