Passing values from id element and calculate price - javascript

I am trying to create a small pricing calculator. I am passing variables from id elements(complex,subject,number_quiz) to formula to calculate and output results to id variable total.
I after passing variables to the formula, it's not calculating and not displaying any results.
function price() {
var com = document.getElementsById('complex').value;
var subject = document.getElementsById('subject').value;
var n_q = document.getElementsById('number_quiz').value;
if (subject == 5 && com == 10) {
var total = (com + subject) n_q;
document.getElementById('total').value = total;
} else if (subject == 7 && com == 10) {
var total = (com + subject) n_q;
document.getElementById('total').value = total;
}
if (subject == 5 && com == 20) {
var total = (com + subject) n_q;
document.getElementById('total').value = total;
} else if (subject == 7 && com == 20) {
var total = (com + subject) n_q;
document.getElementById('total').value = total;
}
}
<div class="container py-5">
<div class="row py-3">
<div class="col-sm-4">
<label>Subject</label>
</div>
<div class="col-sm-4">
<select class="form-control" name="subject" id="subject" onclick="price()">
<option default="">Select Subject</option>
<option value="5">Subject A</option>
<option value="7">Subject A</option>
</select>
</div>
</div>
<div class="row py-3">
<div class="col-sm-4">
<label>Complexity</label>
</div>
<div class="col-sm-4">
<select class="form-control" name="complex" id="complex">
<option default>Select Complexity</option>
<option value="10">Complex Question</option>
<option value="20">Non Complex Question</option>
</select>
</div>
</div>
<div class="row py-3">
<div class="col-sm-4">
<label>Number of questions</label>
</div>
<div class="col-sm-4">
<input type="number" name="number_quiz" id="number_quiz" max="9999" min="1" class="form-control">
</div>
</div>
<div class="row py-3">
<div class="col-sm-4">
<label>Total Net</label>
</div>
<div class="col-sm-4">
<input type="text" readonly="readonly" id="total" onkeyup="total()" name="total" class="form-control bg-white border-0">
</div>
</div>
<div class="row py-3">
<div class="col-sm-4">
</div>
<div class="col-sm-4">
<input type="submit" class="btn btn-danger btn-lg w-50 rounded-pill">
</div>
</div>
</div>

Missing * as already mentioned
getElementById is singular
Use onChange and add it as an eventListener on the container, added benefit, any change will trigger a calculation
You have not told us the manipulation needed in the different ifs, you are missing an else there too
onkeyup="total()" does not exist, and what is it supposed to do?
Note I cast the values to number usining the unary + operator and use 0 if undefined
document.querySelector('.container').addEventListener('change', function() {
const com = +document.getElementById('complex').value || 0;
const subject = +document.getElementById('subject').value || 0;
const n_q = +document.getElementById('number_quiz').value || 0;
const total = (com + subject) * n_q;
if (subject == 5 && com == 10) {
// ...
} else if (subject == 7 && com == 10) {
// ...
} else if (subject == 5 && com == 20) {
// ...
} else if (subject == 7 && com == 20) {
// ...
}
document.getElementById('total').value = total;
});
<div class="container py-5">
<div class="row py-3">
<div class="col-sm-4">
<label>Subject</label>
</div>
<div class="col-sm-4">
<select class="form-control" name="subject" id="subject">
<option default="">Select Subject</option>
<option value="5">Subject A</option>
<option value="7">Subject A</option>
</select>
</div>
</div>
<div class="row py-3">
<div class="col-sm-4">
<label>Complexity</label>
</div>
<div class="col-sm-4">
<select class="form-control" name="complex" id="complex">
<option default>Select Complexity</option>
<option value="10">Complex Question</option>
<option value="20">Non Complex Question</option>
</select>
</div>
</div>
<div class="row py-3">
<div class="col-sm-4">
<label>Number of questions</label>
</div>
<div class="col-sm-4">
<input type="number" name="number_quiz" id="number_quiz" max="9999" min="1" class="form-control">
</div>
</div>
<div class="row py-3">
<div class="col-sm-4">
<label>Total Net</label>
</div>
<div class="col-sm-4">
<input type="text" readonly id="total" name="total" class="form-control bg-white border-0">
</div>
</div>
<div class="row py-3">
<div class="col-sm-4">
</div>
<div class="col-sm-4">
<input type="submit" class="btn btn-danger btn-lg w-50 rounded-pill">
</div>
</div>
</div>

(com + subject)n_q
is incorrect. If you want to multiply it should be...
(com + subject) * n_q
Also the if statements are unnecessary, because you're doing the same action in all of them.

function price()
{
var com = document.getElementById('complex').value;
var subject = document.getElementById('subject').value;
var n_q = document.getElementById('number_quiz').value;
if (subject == 5 && com == 10)
{
var total = (com + subject)*n_q;
document.getElementById('total').value = total;
}
else if (subject == 7 && com == 10) {
var total = (com + subject)*n_q;
document.getElementById('total').value = total;
}
if (subject == 5 && com == 20)
{
var total = (com + subject)*n_q;
document.getElementById('total').value = total;
}
else if (subject == 7 && com == 20) {
var total = (com + subject)*n_q;
document.getElementById('total').value = total;
}
}
<div class="container py-5">
<div class="row py-3">
<div class="col-sm-4">
<label>Subject</label>
</div>
<div class="col-sm-4">
<select class="form-control" name="subject" id="subject" onclick="price()">
<option default="">Select Subject</option>
<option value="5">Subject A</option>
<option value="7">Subject A</option>
</select>
</div>
</div>
<div class="row py-3">
<div class="col-sm-4">
<label>Complexity</label>
</div>
<div class="col-sm-4">
<select class="form-control" name="complex" id="complex" >
<option default>Select Complexity</option>
<option value="10">Complex Question</option>
<option value="20">Non Complex Question</option>
</select>
</div>
</div>
<div class="row py-3">
<div class="col-sm-4">
<label>Number of questions</label>
</div>
<div class="col-sm-4">
<input type="number" name="number_quiz" id="number_quiz" max="9999" min="1" class="form-control">
</div>
</div>
<div class="row py-3">
<div class="col-sm-4">
<label>Total Net</label>
</div>
<div class="col-sm-4">
<input type="text" readonly="readonly" id="total" name="total" class="form-control bg-white border-0">
</div>
</div>
<div class="row py-3">
<div class="col-sm-4">
</div>
<div class="col-sm-4">
<input type="button" onclick="price()" value="Submit"
class="btn btn-danger btn-lg w-50 rounded-pill">
</div>
</div>
</div>
Error 1
To do multiplication you need to use *
var total = (com + subject)*n_q;
Error 2
In your code, you had document.getElementsById which should be document.getElementById
Error 3
In your code on total, you are calling a function total on keyup, which is not defined on your javascript code
Error 4
Your calculation function price is never called

First, I believe you mean var total = (com + subject) * n_q; rather than var total = (com + subject)n_q;.
Second, all if clauses run the same code, so you can remove all the if statements and leave the code as.
Third, you need to change getElementsById to getElementById.
function price()
{
var com = document.getElementById('complex').value;
var subject = document.getElementById('subject').value;
var n_q = document.getElementById('number_quiz').value;
var total = (com + subject) * n_q;
document.getElementById('total').value = total;
}

Related

Show Thousands Separator within input field only

I have added a thousand separator by Javascript keyup to an input field within a standard form:
Form
<form>
<div class="row mt20">
<div class="col-md-3 col-sm-12 col-xs-12">
</div>
<div>
<input id="cal2_txtLoan" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="text" placeholder="วงเงินกู้(บาท)">
</div>
</div>
<div class="row mt20">
<div class="col-md-6 col-sm-9 col-xs-9">
<input id="cal2_txtTenor" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="number" placeholder="ระยะเวลากู้ 1-30 ปี">
</div>
</div>
<div class="row mt20">
<div class="col-md-6 col-sm-9 col-xs-9">
<input id="cal2_txtInterestRate" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="number" placeholder="ดอกเบี้ย(%)">
</div>
</div>
<div class="row mt20">
<div class="col-md-offset-3 col-md-6 col-sm-offset-0 col-sm-9 col-xs-offset-0 col-xs-9">
<div class="row">
<div class="col-xs-6">
<button type="button" id="cal2_btnCalculate" class="button investment-button">คำนวณ</button>
</div>
</div>
</div>
</div>
<div class="row mt20">
<div class="col-md-3 col-sm-12 col-xs-12">
<label class="investment-list">สรุปยอดผ่อนต่อเดือน (บาท)</label> <input id="cal2_txtInstallment" class="wpcf7-form-control wpcf7-text form-control investment-class-form" disabled="disabled" type="text"> <span class="investment-list" style="color:red;">* ผลลัพธ์จากการคำนวณ เป็นเพียงผลการคำนวณเบื้องต้นเท่านั้น โปรดติดต่อธนาคารเพื่อคำนวณยอดที่ถูกต้องอีกครั้งหนึ่ง</span>
</div>
</div>
</form>
Javascript Event Keyup
<script>
var cal2_txtLoan = document.getElementById('cal2_txtLoan');
cal2_txtLoan.addEventListener('keyup', function() {
var val = this.value;
val = val.replace(/[^0-9\.]/g,'');
if(val != "") {
valArr = val.split('.');
valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
val = valArr.join('.');
}
this.value = val;
});
</script>
It works correctly, but now my form cannot submit because of the comma "," in the value
How can I display my decimal separator in the input field, but only submit the value.
Rest of my calculation for reference:
<script>
function CalculatePMT(pv, rate, years) {
return Math.round(pv * (rate / 100 / 12) / (1 - 1 / Math.pow ((1 + rate / 100 / 12) , ( years * 12))));
}
/************** CALCULATE LOAN *************/
$("#cal2_btnCalculate").click(Calculate2);
function Calculate2(event) {
var years = $("#cal2_txtTenor").val();
var rate = $("#cal2_txtInterestRate").val();
var pv = $("#cal2_txtLoan").val();
if (CheckForDigit(years) && CheckForDigit(rate) && CheckForDigit(pv)) {
var ir = (rate / 100) * 100; // For LH, add 1 more
var installment = CalculatePMT(pv, ir, years);
$("#cal2_txtInstallment").val(FormatNumberToString(installment));
$("#cal2_txtMinimumIncome").val(FormatNumberToString(installment ));
} else
alert("ไม่สามารถคำนวนวงเงินสินเชื่อเพื่อการซื้อบ้านได้");
}
/*****************************************/
});
</script
<form onsubmit="return deleteThousandSeparator(event)">
...
</form>
function deleteThousandSeparator(){
const cal2_txtLoan = document.getElementById('cal2_txtLoan');
cal2_txtLoan.value = cal2_txtLoan.value.replace('.','')
}

Decimal Separator within input field

I have added a thousand separator by Javascript keyup to an input field within a standard form. Now my form cannot submit because of the comma "," in the value.
How can I edit my current code or add a new function to remove the comma when submitting the form.
Javascript Event Keyup
<script>
var cal2_txtLoan = document.getElementById('cal2_txtLoan');
cal2_txtLoan.addEventListener('keyup', function() {
var val = this.value;
val = val.replace(/[^0-9\.]/g,'');
if(val != "") {
valArr = val.split('.');
valArr[0] = (parseInt(valArr[0],10)).toLocaleString();
val = valArr.join('.');
}
this.value = val;
});
</script>
Form
<form>
<div class="row mt20">
<div class="col-md-3 col-sm-12 col-xs-12">
</div>
<div>
<input id="cal2_txtLoan" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="text" placeholder="วงเงินกู้(บาท)">
</div>
</div>
<div class="row mt20">
<div class="col-md-6 col-sm-9 col-xs-9">
<input id="cal2_txtTenor" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="number" placeholder="ระยะเวลากู้ 1-30 ปี">
</div>
</div>
<div class="row mt20">
<div class="col-md-6 col-sm-9 col-xs-9">
<input id="cal2_txtInterestRate" class="wpcf7-form-control wpcf7-text form-control investment-class-form" type="number" placeholder="ดอกเบี้ย(%)">
</div>
</div>
<div class="row mt20">
<div class="col-md-offset-3 col-md-6 col-sm-offset-0 col-sm-9 col-xs-offset-0 col-xs-9">
<div class="row">
<div class="col-xs-6">
<button type="button" id="cal2_btnCalculate" class="button investment-button">คำนวณ</button>
</div>
</div>
</div>
</div>
<div class="row mt20">
<div class="col-md-3 col-sm-12 col-xs-12">
<label class="investment-list">สรุปยอดผ่อนต่อเดือน (บาท)</label> <input id="cal2_txtInstallment" class="wpcf7-form-control wpcf7-text form-control investment-class-form" disabled="disabled" type="text"> <span class="investment-list" style="color:red;">* ผลลัพธ์จากการคำนวณ เป็นเพียงผลการคำนวณเบื้องต้นเท่านั้น โปรดติดต่อธนาคารเพื่อคำนวณยอดที่ถูกต้องอีกครั้งหนึ่ง</span>
</div>
</div>
</form>
Check out: How to convert a locale string (currency) back into a number?
let num = parseFloat(yourString.replace(/[^0-9\.]/g,''));
(You actually have the answer in your own code 😉)
Update: Here's an example.
let myString = "1,250,856.5867";
function convertToFloat(string) {
let num = parseFloat(string.replace(/[^0-9\.]/g,''));
return num;
}
/* Test the function in console */
console.log(convertToFloat(myString));
Output will be: 1250856.5867

How do I disable a select option based on another select option?

I've been wondering if I can disable a select option based on the value length of another select option.
var start = 2010;
var end = 2030;
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 start = 2010;
var end = 2030;
var options = "";
for (var year = start; year <= end; year++) {
options += "<option>" + year + "</option>";
}
document.getElementById("idTahunBerlakuS").insertAdjacentHTML(
"beforeend", options);
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().length == 0 ||
$('#idtrainingName').val().length == 0) {
alert("ISI SEMUA FORM TERLEBIH DAHULU");
} else {
debugger;
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');
/* redirecting to home of barang */
debugger;
} else {
alert("Data salah");
}
},
error: function(model) {
debugger;
}
});
}
});
$(".clSelectKiri").change(function() {
if ($('#idTahunBerlaku').val().length == 0 &&
$('#idBulanBerlaku').val().length == 0) {
$(".clTgglKanan").attr("disabled", "disabled");
} else {
$(".clTgglKanan").removeAttr("disabled");
}
}).trigger("change");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></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="" 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="" 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">Batal</button>
<button type="button" class="btn clBtnMdl" id="idBtnSimpanSimpan">Simpan</button>
</div>
</div>
</div>
</div>
</form>
When I select a value in the .clSelectKiri value length == 0 I want the .clTgglKanan to be disabled. And there's a hidden option, is that affecting it?
This is the code I've been working, but it isn't working. Does anyone has any idea why?
In your if statement that disables the lower two select elements you just need to change .val().length == 0 to .val and that will disable them when the top two are selected.
var start = 2010;
var end = 2030;
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 start = 2010;
var end = 2030;
var options = "";
for (var year = start; year <= end; year++) {
options += "<option>" + year + "</option>";
}
document.getElementById("idTahunBerlakuS").insertAdjacentHTML(
"beforeend", options);
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().length == 0 ||
$('#idtrainingName').val().length == 0) {
alert("ISI SEMUA FORM TERLEBIH DAHULU");
} else {
debugger;
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');
/* redirecting to home of barang */
debugger;
} else {
alert("Data salah");
}
},
error: function(model) {
debugger;
}
});
}
});
$(".clSelectKiri").change(function() {
if ($('#idTahunBerlaku').val() && $('#idBulanBerlaku').val()) {
$(".clTgglKanan").attr("disabled", false);
} else {
$(".clTgglKanan").attr("disabled", true);
}
}).trigger("change");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></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="" 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="" 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">Batal</button>
<button type="button" class="btn clBtnMdl" id="idBtnSimpanSimpan">Simpan</button>
</div>
</div>
</div>
</div>
</form>

Optimize the repetitive code for adding new option to select jquery

Here is my fiddle : DEMO
I have repeated codes for adding new options to rule and event category select. How do I optimize the same to eliminate the repeated code?
//Adding new category for event
$(document).on('click', '.addevent', function() {
var found = false; // Track if new value was found in list
// Loop through list options
$("#categoryevent > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if ($("#new-option-event").val().trim().toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!")
found = true; // Set flag if value exists
$('#new-option-event').val('');
}
});
// If not found
if ($('#new-option-event').val().trim() != '') {
if (!found) {
// Create new option and append to list
var val = $("#new-option-event").val().trim();
var opt = '<option>' + val + '</option>';
$('#categoryevent').append(opt);
$('#categoryevent').val(val);
$('#new-option-event').val('');
$("#categoryevent").click();
}
}
});
Here you go - a common function helps a lot:
//Adding new category for rule
$(document).on('click', '.addrule', function() {
AddElement("categoryrule", "new-option-rule");
});
//Adding new category for event
$(document).on('click', '.addevent', function() {
AddElement("categoryevent", "new-option-event");
});
function AddElement(selectId, newElementId){
var found = false; // Track if new value was found in list
// Loop through list options
$( "#" + selectId + " > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if ($("#" + newElementId).val().trim().toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!")
found = true; // Set flag if value exists
$('#' + newElementId).val('');
}
});
// If not found
if ($('#' + newElementId).val().trim() != '') {
if (!found) {
// Create new option and append to list
var val = $("#" + newElementId).val().trim();
var opt = '<option>' + val + '</option>';
$('#' + selectId).append(opt);
$('#' + selectId).val(val);
$('#' + newElementId).val('');
$("#" + selectId).click();
}
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Rule Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryrule" name="category">
<option>Humidity</option>
<option>Temperature</option>
<option>Rule Type3</option>
<option>Rule Type4</option>
<option>Rule Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addrule">Add Category</button>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Event Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryevent" name="category">
<option>SMS</option>
<option>Email</option>
<option>Invoke API</option>
<option>Event Type4</option>
<option>Event Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addevent">Add Category</button>
</div>
</div>
</div>
<div class="actionConfig">
</div>
Here you go with some optimised code https://jsfiddle.net/3tLx884e/2/
//Adding new category for rule
$(document).on('click', '.addrule', function() {
var found = false; // Track if new value was found in list
// Loop through list options
var text = $("#new-option-rule").val().trim();
$("#categoryrule > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if (text.toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!");
found = true; // Set flag if value exists
}
if((idx + 1) === $('#categoryrule > option').length){
if ( !found && (text != '')) {
// Create new option and append to list
$('#categoryrule')
.append('<option>' + text + '</option>')
.val(text);
}
$('#new-option-rule').val('');
}
});
// If not found
});
//Adding new category for event
$(document).on('click', '.addevent', function() {
var found = false; // Track if new value was found in list
// Loop through list options
$("#categoryevent > option").each(function(idx, el) {
// Compare (case-insensitive) new value against list values
if ($("#new-option-event").val().trim().toLowerCase() === el.textContent.toLowerCase()) {
alert("Category already exists!")
found = true; // Set flag if value exists
$('#new-option-event').val('');
}
});
// If not found
if ($('#new-option-event').val().trim() != '') {
if (!found) {
// Create new option and append to list
var val = $("#new-option-event").val().trim();
var opt = '<option>' + val + '</option>';
$('#categoryevent').append(opt);
$('#categoryevent').val(val);
$('#new-option-event').val('');
$("#categoryevent").click();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Rule Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryrule" name="category">
<option>Humidity</option>
<option>Temperature</option>
<option>Rule Type3</option>
<option>Rule Type4</option>
<option>Rule Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addrule">Add Category</button>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Event Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryevent" name="category">
<option>SMS</option>
<option>Email</option>
<option>Invoke API</option>
<option>Event Type4</option>
<option>Event Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addevent">Add Category</button>
</div>
</div>
</div>
<div class="actionConfig">
</div>
Hope this will help you.
This is my take on the problem, following jquery's slogan: "write less, do more" ...
I reduced the code further by working on local context. I. e. I only need to define one click event for everything. The click function itself figures out, what to change. It does not need any ids to do its job:
//Adding new category for rule and event
$('.form-group').on('click', 'button', addElement);
function addElement(){
var $grp=$(this).closest('.form-group'),
ival=$('input:text',$grp).val().trim(), // new input value
$sel=$('select',$grp.prev()), // select element
opts=$.makeArray($('option',$sel).map(function(i,op){
return op.textContent.toLowerCase(); }));
if ($.inArray(ival.toLowerCase(),opts)===-1){ // check existing option values
$sel.append('<option value="'+ival+'" selected>'+ival+'</option>');
}
else {alert(ival+' exists already in '+$sel[0].id);}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Rule Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryrule" name="category">
<option>Humidity</option>
<option>Temperature</option>
<option>Rule Type3</option>
<option>Rule Type4</option>
<option>Rule Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-rule" name="addcategoryrule">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addrule">Add Category</button>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2" for="category">Event Category:</label>
<div class="col-sm-8">
<select class="form-control" id="categoryevent" name="category">
<option>SMS</option>
<option>Email</option>
<option>Invoke API</option>
<option>Event Type4</option>
<option>Event Miscellaneous</option>
</select>
</div>
</div>
<div class="form-group">
<label class="control-label col-sm-2"></label>
<div class="col-sm-8">
<div class="col-sm-8" style="padding-left:0px;">
<input type="text" class="form-control center-block" id="new-option-event" name="addcategoryevent">
</div>
<div class="col-sm-2" style="padding-left:0px;">
<button class="btn btn-md addevent">Add Category</button>
</div>
</div>
</div>
<div class="actionConfig">
</div>

Form field values sum in jQuery

I can't seem to get this to work for a project I'm doing. Basically I'm trying to get the values in the "Revenue" fields to total at the bottom in the "Total Revenue" field.
I've made a JSFiddle which hopefully will make it easier to understand-
HTML markup:
<div class="form-group">
<label class="control-label col-md-2">April</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control" name="AprilInput" placeholder="eg. 35,328" type="text" id="AprilInput"></input>
</div>
</div>
<label class="control-label col-md-1">Revenue</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control" name="Output" id="AprilOutput" placeholder="0" type="text" readonly></input>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">May</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control" name="MayInput" placeholder="eg. 35,328" type="text" id="MayInput"></input>
</div>
</div>
<label class="control-label col-md-1">Revenue</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control1" name="Output" id="MayOutput" placeholder="0" type="text" readonly></input>
</div>
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2">June</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control" name="JuneInput" placeholder="eg. 35,328" type="text" id="JuneInput"></input>
</div>
</div>
<label class="control-label col-md-1">Revenue</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control1" name="Output" id="JuneOutput" placeholder="0" type="text" readonly></input>
</div>
</div>
</div>
<br/>
<span class="form-horizontal">
<div class="row">
<div class="col-lg-12">
<div class="widget-container fluid-height clearfix">
<div class="heading">
<i class="icon-reorder"></i>Annual Total
</div>
<div class="widget-content padded">
<div class="form-group">
<label class="control-label col-md-6">Total Revenue</label>
<div class="col-md-3">
<div class="input-group">
<span class="input-group-addon">$</span><input class="form-control" name="TotalOutput" id="TotalOutput" placeholder="0" type="text" readonly></input>
</div>
</div>
</div>
You could tidy the code up a little:
function SetupInput(obj,output,sumfunction){
$(obj).keyup(function(){
var n = parseInt($(this).val());
var n = this.value.replace(/,/g, "");
if(n <= 155000) {
$(output).val(numberWithCommas((n/100*70).toFixed(0)));
}
else if(n <= 175000) {
$(output).val(numberWithCommas((n/100*75).toFixed(0)));
}
else {
$(output).val(numberWithCommas((n/100*80).toFixed(0)));
}
sumfunction();
});
}
SetupInput($('#AprilInput')[0],$('#AprilOutput')[0],calculateSum);
SetupInput($('#MayInput')[0],$('#MayOutput')[0],calculateSum);
SetupInput($('#JuneInput')[0],$('#JuneOutput')[0],calculateSum);
function numberWithCommas(x) {
return x.toString().replace(/\B(?=(?:\d{3})+(?!\d))/g, ",");
}
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".form-control1").each(function() {
//add only if the value is number
var value=this.value.replace(',','');//remove ','
if(!isNaN(value) && value.length!=0) {
sum += parseFloat(value);
console.log(this.id,sum);
}
});
//.toFixed() method to roundoff the final sum
$("#TotalOutput").val(sum.toFixed(0));
}
Check out the jsfiddle: http://jsfiddle.net/2jY6P/43/
You are looping though Output tag. Change it to .form-contol:
$(".form-control").each(function() { /* ... */ }
And not .html, but .val():
`$("#TotalOutput").val(sum.toFixed(0));`
i edited you code: http://jsfiddle.net/2jY6P/38/
changed:
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$("input[name='Output']").keyup(function(){
calculateSum();
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$("input[name='Output']").each(function() {
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method to roundoff the final sum
$("#TotalOutput").val(sum.toFixed(0));
}
$('Output') should be input $("[name='Output']")
$("#TotalOutput").html(sum.toFixed(0));
should be $("#TotalOutput").val(sum.toFixed(0));
I put some changes in
http://jsfiddle.net/2jY6P/39/
$(document).keyup(function() {
var sumRevenue = 0;
$.each($(".revenue"), function() {
var val = $.trim($(this).val());
if(val != "")
sumRevenue += parseFloat(val);
});
$("#sumrevenue").val(sumRevenue);
});
function calculateTotalREv(){
var totalRev = 0;
$("input[name='Output']").each(function() {
totalRev = eval(total+parseFloat($(this).val()));
});
alert(totalRev);
}
calculateTotalREv();

Categories

Resources