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>
Related
What I want to do is replace the id for every input. I have several inputs in my page.
This is the coding for some user input
<div class="row">
<div class="col">
<div class="form-group row">
<label class="col-md-2 col-form-label" for="daddr3_1">Address 3:</label>
<div class="col-md-9">
<input class="form-control" rows="1" maxlength="30" type="text" id="daddr3_1" name="daddr3[]" placeholder="Third line of address as in Identity Card (optional)">
</div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<?php
include_once "common.php";
$common = new Common();
$countries = $common->getCountry($connection);
?>
<div class="form-group row">
<label class="col-md-3 col-form-label" for="countryId_1">Country:</label>
<div class="col-md-5">
<select name="countryId[]" id="countryId_1" class="form-control" onchange="getStateByCountry();">
<option>Country</option>
<?php
if ($countries->num_rows > 0 ){
while ($country = $countries->fetch_object()) {
$countryName = $country->name; ?>
<option value="<?php echo $country->id; ?>"><?php echo $countryName;?></option>
<?php }
}
?>
</select>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<label class="col-md-3 col-form-label" for="stateId_1">State:</label>
<div class="col-md-5">
<select name="stateId[]" id="stateId_1" class="form-control" onchange="getCityByState();getPostalByState()">
<option>State</option>
</select>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<label class="col-md-3 col-form-label" for="cityDiv_1">City:</label>
<div class="col-md-5">
<select name="cityDiv[]" id="cityDiv_1" class="form-control">
<option value="">City</option>
</select>
</div>
</div>
</div>
<div class="col">
<div class="form-group row">
<label class="col-md-3 col-form-label" for="dpostal">Postal:</label>
<div class="col-md-5">
<select name="postalDiv[]" id="postalDiv_1" class="form-control">
<option>Postal</option>
</select>
</div>
</div>
</div>
</div>
I want to increase the _1 of the input if user add more than one item by duplicating the form.
This is the script to replace the _1 everytime user duplicate the form.
var attrs = ['for', 'id', 'name'];
function resetAttributeNames(section) {
var tags = section.find('input, label, select'), idx = section.index();
tags.each(function() {
var $this = $(this);
$.each(attrs, function(i, attr) {
var attr_val = $this.attr(attr);
if (attr_val) {
$this.attr(attr, attr_val.replace(/_\d+$/, '_'+(idx + 1)))
}
})
})
}
As you can see, in user input for country, state, city, and postal I used onchange function. I wonder if it ain't working because of the onchange function. Because the id can be replaced for Address 3 input. Only the list I mention above is not working.
This is the script of onchange function
<script>
function getStateByCountry() {
var countryId = $("#countryId_1").val();
$.post("ajax.php",{getStateByCountry:'getStateByCountry',countryId:countryId},function (response) {
var data = response.split('^');
$("#stateId_1").html(data[1]);
});
}
function getCityByState() {
var stateId = $("#stateId_1").val();
$.post("ajax.php",{getCityByState:'getCityByState',stateId:stateId},function (response) {
var data = response.split('^');
$("#cityDiv_1").html(data[1]);
});
}
function getPostalByState() {
var stateId = $("#stateId_1").val();
$.post("ajax.php",{getPostalByState:'getPostalByState',stateId:stateId},function (response) {
var data = response.split('^');
$("#postalDiv_1").html(data[1]);
});
}
function enable(){
var check = document.getElementById("check");
var btn = document.getElementById("btn");
if(check.checked){
btn.removeAttribute("disabled");
}
else{
btn.disabled = "true";
}
}
</script>
Any help is appreciated :)
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;
}
I'm trying to make a MODAL step by step validating each step, but I can only validate the input with error, but I can not validate the select.
wanted that when the value of the select is equal to ZERO (0) the validation occurs as well.
Could someone help me with this JS? I would be extremely grateful.
$(document).ready(function () {
var navListItems = $('div.setup-panel div a'),
allWells = $('.setup-content'),
allNextBtn = $('.nextBtn');
allWells.hide();
navListItems.click(function (e) {
e.preventDefault();
var $target = $($(this).attr('href')),
$item = $(this);
if (!$item.hasClass('disabled')) {
navListItems.removeClass('btn-primary').addClass('btn-default');
$item.addClass('btn-primary');
allWells.hide();
$target.show();
$target.find('input:eq(0)').focus();
$target.find('select:eq(0)').focus();
}
});
allNextBtn.click(function(){
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),
curInputs = curStep.find("input[type='text'],input[type='url'],select[type='text']"),
isValid = true;
$(".form-group").removeClass("has-error");
for(var i=0; i<curInputs.length; i++){
if (!curInputs[i].validity.valid){
isValid = false;
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
if (isValid)
nextStepWizard.removeAttr('disabled').trigger('click');
});
$('div.setup-panel div a.btn-primary').trigger('click');
});
<div class="container">
<div class="row">
<h2>Multistep form wizard on modal</h2>
<div class="center"><button data-toggle="modal" data-target="#requestform" class="btn btn-primary center-block">Click Me</button></div>
</div>
</div>
<div class="modal fade" id="requestform" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h3 class="modal-title" id="lineModalLabel">Proposta</h3>
</div>
<div class="modal-body">
<!-- Steps starts here -->
<div class="requestwizard">
<div class="requestwizard-row setup-panel">
<div class="requestwizard-step">
1
<p>Selecione um contato</p>
</div>
<div class="requestwizard-step">
2
<p>Selecione um curso</p>
</div>
<div class="requestwizard-step">
3
<p>Forma de pagamento</p>
</div>
</div>
</div>
<br>
<form role="form">
<div class="row setup-content" id="step-1">
<div class="col-xs-12">
<div class="col-md-12">
<div class="form-group">
<input maxlength="100" type="text" required="required" class="form-control" placeholder="Contato" />
</div>
<hr>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Próximo</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-2">
<div class="col-xs-12">
<div class="col-md-12">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<select class="form-control custom-select" id="filtercountry">
<option value="0" class="selectcountry">Country</option>
<option value="201" class="selectcountry">Australia</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<select class="form-control custom-select" id="filtercity">
<option value="0" class="selectcity">City</option>
<option value="101" class="selectcity">California</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<select class="form-control custom-select" id="filterregion">
<option value="0" class="selectregion">Region</option>
<option value="3" class="selectregion">Brazil</option>
</select>
</div>
</div>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<input maxlength="200" type="text" required="required" class="form-control" placeholder="Curso" />
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Próximo</button>
</div>
</div>
</div>
<div class="row setup-content" id="step-3">
<div class="col-xs-12">
<div class="col-md-12">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><spring:message code="label.firstinstallment"/></label>
<input type="text" class="form-control" placeholder="First installment" id="finstallment" name="finstallment" required>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><spring:message code="label.numberparcels"/></label>
<select class="form-control custom-select" name="parcels" required>
<option value="0">0</option>
<option value="1">1</option>
</select>
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label class="control-label"><spring:message code="label.firstinvoice"/></label>
<input type="date" class="form-control" placeholder="Invoice maturity" name="expiration_date" required>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label class="control-label"><spring:message code="label.selectpaymentplan"/></label>
<select class="form-control custom-select" name="payment_plan" required>
<option value="1">Bank slip</option>
</select>
</div>
</div>
</div>
<button class="btn btn-primary nextBtn btn-lg pull-right" type="button" >Enviar</button>
</div>
</div>
</div>
</form>
<!-- Form ends here -->
</div>
</div>
</div>
</div>
you need to check for the control type in the for loop inside allNextBtn.click event like this:
for(var i=0; i<curInputs.length; i++){
//if the control is select check the selected index if it is ZERO
if ( $(curInputs[i]).is('select') && (curInputs[i].selectedIndex === 0)
{
isValid = false;
}
//else check control validity
else if (!curInputs[i].validity.valid)
{
isValid = false;
}
if(!isValid)
{
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
and change this line:
curInputs = curStep.find("input[type='text'],input[type='url'],select[type='text']"),
to this:
curInputs = curStep.find("input[type='text'],input[type='url'],select"),
here is the full js code:
$(document).ready(function () {
var navListItems = $('div.setup-panel div a'),
allWells = $('.setup-content'),
allNextBtn = $('.nextBtn');
allWells.hide();
navListItems.click(function (e) {
e.preventDefault();
var $target = $($(this).attr('href')),
$item = $(this);
if (!$item.hasClass('disabled')) {
navListItems.removeClass('btn-primary').addClass('btn-default');
$item.addClass('btn-primary');
allWells.hide();
$target.show();
$target.find('input:eq(0)').focus();
$target.find('select:eq(0)').focus();
}
});
allNextBtn.click(function(){
var curStep = $(this).closest(".setup-content"),
curStepBtn = curStep.attr("id"),
nextStepWizard = $('div.setup-panel div a[href="#' + curStepBtn + '"]').parent().next().children("a"),
curInputs = curStep.find("input[type='text'],input[type='url'],select"),
isValid = true;
$(".form-group").removeClass("has-error");
//BEGIN EDIT
for(var i=0; i<curInputs.length; i++){
//if the control is select check the selected index if it is ZERO
if ( $(curInputs[i]).is('select') && (curInputs[i].selectedIndex === 0))
{
isValid = false;
}
//else check control validity
else if (!curInputs[i].validity.valid)
{
isValid = false;
}
if(!isValid)
{
$(curInputs[i]).closest(".form-group").addClass("has-error");
}
}
//END EDIT
if (isValid)
nextStepWizard.removeAttr('disabled').trigger('click');
});
$('div.setup-panel div a.btn-primary').trigger('click');
});
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>
I wrote a small script. I have a form in my page. It takes data from MySQL Database. After that, When user select some options from select panels, I need JS will do math summation and write total in a div/input field.
I wrote the page and got errors. I changed a lot of things after searched similar problems on net and here.
I used parseInt($.. ,10) , document.getElementById("testID").innerHTML , document.getElementById("testID").value , document.getElementById("testID").val() and etc...
So, I'm asking your help to correct my errors.
Thanks
Here is the Jsfiddle page link;
jsfiddle page
My Code (this is the latest version that I have) ;
JS:
<script type="text/javascript">
function updatesum() {
var T = 0;
var d = document;
var A = d.getElementById("araclar").val();
var M = d.getElementById("varis").val();
var K = d.getElementById("kisiler").val();
var B = d.getElementById("bavullar").val();
var C = d.getElementById("cocuklar").val();
var Ck = d.getElementById("cocukKoltuk").val();
T = parseInt('A' ,10) * parseInt('M' ,10);
document.getElementById("toplamm").innerHTML = T;
}
</script>
PHP:
<form action="subscribe.php" id="subscribe" method="post" name="subscribe">
<div class="row">
<div class="col-xs-12 col-sm-10">
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-3">
<label>NAME<input class="form-control" name="name" placeholder="NAME" type="text"></label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<label>SURNAME<input class="form-control" name="surname" placeholder="SURNAME" type="text"></label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<label>TELEPHONE<input class="form-control" name="date" placeholder="TELEPHONE" type="tel"></label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<label>EMAIL<input class="form-control" name="email" placeholder="EMAIL" type="email"></label>
</div>
<hr />
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-3">
<label>FROM:<select class="form-control" name="kalkis" id="kalkis" onchange="bolegler(this.value);sifirla();">
<option value="">Please Select</option>
<?php
$boleg= mysql_query("SELECT * FROM areas WHERE ust LIKE 0");
while($bolges = mysql_fetch_array($boleg)) {
echo '<option value="'.$bolges['id'].'">'.$bolges['isim'].'</option>';
}
?>
</select></label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3" id="txtHint">
<!-- This Code will change after #kalkis change by JS start-->
<label>TO:<select name="varis" class="form-control">
<option value="">Please Select</option>
</select></label>
<!-- This Code will change after #kalkis change by JS end-->
</div>
<div id="datetimepicker" class="col-xs-12 col-sm-6 col-md-3 input-append date">
<label>REZERVATION DATE
<input type="text" class="col-xs-8 form-control" name="rezervasyon" style="float:left;"></input>
<span class="add-on col-xs-2" style="float: left; margin: -39px 0; font-size: 23px;"><i class="fa fa-calendar"></i>
</span>
</label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<label>CAR:
<select name="car" id="car" class="form-control" onchange="updatesum();">
<option value="0">Please Select</option>
<?php
$ara= mysql_query("SELECT * FROM cars");
while($arac = mysql_fetch_array($ara)) {
echo '<option value="'.$arac['price'].'" class="'.$arac['id'].'">'.$arac['isim'].'</option>';
}
?>
</select>
</label>
</div>
</div>
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-3">
<label>PERSON QTY
<select name="persons" id="persons" class="form-control" onchange="updatesum();">
<option value="0">Please Select</option>
<?php
$kis= mysql_query("SELECT * FROM person");
while($person = mysql_fetch_array($kis)) {
echo '<option value="'.$person['price'].'" class="'.$person['qty'].'">'.$person['qty'].'</option>';
}
?>
</select>
</label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<label>bag QTY
<select name="bags" id="bags" class="form-control" onchange="updatesum();">
<option value="0">Please Select</option>
<?php
$bav= mysql_query("SELECT * FROM bag");
while($bag = mysql_fetch_array($bav)) {
echo '<option value="'.$bag['price'].'" class="'.$bag['qty'].'">'.$bag['qty'].'</option>';
}
?>
</select>
</label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3">
<label>KID QTY
<select name="cocuklar" id="cocuklar" class="form-control" onchange="updatesum();cocukla();">
<option value="0">Please Select</option>
<?php
$coc= mysql_query("SELECT * FROM kidqty");
while($kid = mysql_fetch_array($coc)) {
echo '<option value="'.$kid['price'].'" class="'.$kid['qty'].'">'.$kid['qty'].'</option>';
}
?>
</select>
</label>
</div>
<div class="col-xs-12 col-sm-6 col-md-3" id="koltukalani">
<label>KID CHAIR
<select name='kidchair' id='kidchair' class='form-control' onchange='updatesum();'>
<option value='0'>Please Select</option>
<option value='0'>Do no Want</option>
<option value='<?php echo $genel['kidchair']; ?>'>Need a Kid Chair</option>
</select>
</label>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-2">
<button class="form-control submit-button" id="submit" type="submit">SUBMIT</button>
<br />
TOTAL AMOUNT:
<div id="toplamm" class="toplamm">0</div>
</div>
</div>
</form>
And the Other Codes:
function sifirla:
<script type="text/javascript">
function sifirla() {
document.getElementById("toplamm").innerHTML = "0";
}
</script>
function cocukla:
<script type="text/javascript">
function cocukla() {
var cocuk = parseInt(document.getElementById("cocuklar").value);
if (cocuk < "1") {
document.getElementById("kidchair").innerHTML = " ";
}
else {
document.getElementById("kidchair").innerHTML = "<label>KID CHAIR <select name='kidchair' id='kidchair' class='form-control' onchange='updatesum();'> <option value='0'>Please Select</option> <option value='0'>Do not Want</option> <option value='<?php echo $genel['kidchair']; ?>'>Need a Kid Chair</option> </select> </label>"; }
}
</script>
In this line T = parseInt('A' ,10) * parseInt('M' ,10); you are using trying to get the ASCII code of char A and char M. Whereas you should be parsing variables A and M to integer.
You will need to modify your function as below to get the correct numbers-
T = parseInt(A ,10) * parseInt(M ,10);
Updated as per comment -
Use value instead of val() for getting the values form html id tags.
T = parseInt(A ,10) * parseInt(M ,10) + parseInt(K ,10) + parseInt(B ,10) + parseInt(C ,10) + parseInt(Ck ,10);