Very much new to JS and so far I did get what I needed but its a chaos.
I have three classes aer, bsa and sf who have their own div space and by default, they have Bootstrap 4's d-none (display none) class. Now when aer is selected from a drop-down list d-none should be removed and bsa and sf shouldn't change (because they already have d-none in them). Then when I select bsa, d-none should be removed and aer should have d-none, and for bsa nothing should happen. Same goes to sf.
I was able to get this done by the following JQuery:
const aer = $('.aer');
const bsa = $('.bsa');
const sf = $('.sf');
// Encoding algorithm
$('select[id=id_encoding_algorithm_name]').change(function () {
console.log($(this).val());
switch ($(this).val()) {
case "AER":
if(aer.hasClass('d-none')) {
aer.each(function () {
$(this).removeClass('d-none');
});
}
if (!bsa.hasClass('d-none')) {
bsa.each(function () {
$(this).addClass('d-none');
});
}
if (!sf.hasClass('d-none')) {
sf.each(function () {
$(this).addClass('d-none');
});
}
break;
case "BSA":
if(bsa.hasClass('d-none')) {
bsa.each(function () {
$(this).removeClass('d-none');
});
}
if (!aer.hasClass('d-none')) {
aer.each(function () {
$(this).addClass('d-none');
});
}
if (!sf.hasClass('d-none')) {
sf.each(function () {
$(this).addClass('d-none');
});
}
break;
case "SF":
if(sf.hasClass('d-none')) {
sf.each(function () {
$(this).removeClass('d-none');
});
}
if (!aer.hasClass('d-none')) {
aer.each(function () {
$(this).addClass('d-none');
});
}
if (!bsa.hasClass('d-none')) {
bsa.each(function () {
$(this).addClass('d-none');
});
}
break;
}
});
This is too much of code for toggling a class (I guess), is there a better way to do it?
Update 1:
HTML Code (only div code):
<div class="pt-4">
<div class="card">
<div class="card-header">
Encoding Algorithm
</div>
<div class="card-body">
<div class="form-group row">
<label for="Encoding Algorithm Name" class="col-sm-2 col-form-label align-self-center">Encoding
Algorithm Name</label>
<div class="col-sm-9 align-self-center">
<select name="encoding_algorithm_name" class="form-control" id="id_encoding_algorithm_name">
<option value="AER" selected>Address Event Representation</option>
<option value="BSA">Ben's Spiker Algorithm</option>
<option value="SF">Step Forward Algorithm</option>
</select>
</div>
<div class="col-sm-1 align-self-center">
<i class="fas fa-info-circle"></i>
</div>
</div>
<div class="form-group row aer d-none">
<label for="Aer Spike Threshold Value" class="col-sm-2 col-form-label align-self-center">Aer
Spike Threshold Value</label>
<div class="col-sm-9 align-self-center">
<input type="text" name="aer_spike_threshold_value" value="0.5" class="form-control" required id="id_aer_spike_threshold_value">
</div>
<div class="col-sm-1 align-self-center">
<i class="fas fa-info-circle"></i>
</div>
</div>
<div class="form-group row bsa d-none">
<label for="Num Filters" class="col-sm-2 col-form-label align-self-center">Num
Filters</label>
<div class="col-sm-9 align-self-center">
<input type="number" name="num_filters" value="1" class="form-control" required id="id_num_filters">
</div>
<div class="col-sm-1 align-self-center">
<i class="fas fa-info-circle"></i>
</div>
</div>
<div class="form-group row bsa d-none">
<label for="Threshold Vec" class="col-sm-2 col-form-label align-self-center">Threshold
Vec</label>
<div class="col-sm-9 align-self-center">
<input type="text" name="threshold_vec" value="0.9" class="form-control" required id="id_threshold_vec">
</div>
<div class="col-sm-1 align-self-center">
<i class="fas fa-info-circle"></i>
</div>
</div>
<div class="form-group row bsa d-none">
<label for="Filter Order Vec" class="col-sm-2 col-form-label align-self-center">Filter
Order Vec</label>
<div class="col-sm-9 align-self-center">
<input type="text" name="filter_order_vec" value="24" class="form-control" required id="id_filter_order_vec">
</div>
<div class="col-sm-1 align-self-center">
<i class="fas fa-info-circle"></i>
</div>
</div>
<div class="form-group row bsa d-none">
<label for="Filter Cutoff Vec" class="col-sm-2 col-form-label align-self-center">Filter
Cutoff Vec</label>
<div class="col-sm-9 align-self-center">
<input type="text" name="filter_cutoff_vec" value="0.1255" class="form-control" required id="id_filter_cutoff_vec">
</div>
<div class="col-sm-1 align-self-center">
<i class="fas fa-info-circle"></i>
</div>
</div>
</div>
</div>
</div>
Your code can be further simplified.
You can execute the removeClass method on the whole selection at once.
Remove a single class, multiple classes, or all classes from each
element in the set of matched elements.
You really don't have to check if a selection has a class in order to remove it.
So, the code can be simplified as:
case "AER":
aer.removeClass('d-none');
bsa.addClass('d-none');
sf.addClass('d-none');
Same applies to other cases too.
Why so much of conditions?
You can simply do it by
$('select[id=id_encoding_algorithm_name]').change(function () {
console.log($(this).val());
$(aer, bsa, sf).addClass('d-none');
switch ($(this).val()) {
case "AER":
aer.removeClass('d-none');
break;
case "BSA":
bsa.removeClass('d-none');
break;
case "SF":
sf.removeClass('d-none');
break;
}
});
or if you can change values to aer, bsa, sf instead of AER, BSA it will simply become
$('select[id=id_encoding_algorithm_name]').change(function () {
console.log($(this).val());
$(aer, bsa, sf).addClass('d-none');
$("." + $(this).val()).removeClass('d-none');
});
You could use toggleClass() as well in jQuery.
aer.toggleClass('d-none')
Do check the below jsFiddle:
https://jsfiddle.net/ulric_469/tyf5epk2/11/
JScode:
$('select[id=id_encoding_algorithm_name]').change(function () {
$(".common-class").addClass('d-none');
let currentClass = $(this).val();
currentClass = currentClass && currentClass.toLowerCase();
$("."+currentClass).removeClass('d-none');
});
I have added one common class to html you can check the same in JSfiddle
I would advice you to use jQuery#toggleClass method with condition to get more control against your code:
const divs = $('.aer, .bsa, .sf');
// Encoding algorithm
$('select#id_encoding_algorithm_name').change(function () {
const value = $(this).val().toLowerCase();
divs.each(function(index, el){
$(el).toggleClass('d-none', !$(el).hasClass(value))
});
});
Related
Dears, I made a javascript function when checkbox is checked to enable some controllers and when unchecked disable the same controllers and clear their data, it works fine in the first click only, which means if I check the checkbox and select data, then unchecked the checkbox it clear data from input boxes and hide the datetimepicker. BUT if check the checkbox for the second time and select data, then unchecked the checkbox, it does not clear data but hide the time picker.
HTML
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 margin-bottom-10 padding-none">
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-12">
<div class="form-group">
<div class="form-check margin-top-30">
<label>
<input ng-model="attend" type="checkbox" name="check" ng-change="checkattendance()"> <span class="label-text">Attendance Time</span>
</label>
</div>
</div>
</div>
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-12">
<div class="form-group">
<div class="col-xs-12">
<label class="control-label" for="name">Operator<span class="danger">*</span></label>
</div>
<div class="col-xs-12">
<select ng-disabled="!attend" ng-show="lang==0" class="form-control input-sm" ng-model="opinname" ng-options="o.opid as o.openm for o in Operator"></select>
<select ng-disabled="!attend" ng-show="lang==1" class="form-control input-sm" ng-model="opinname" ng-options="o.opid as o.opanm for o in Operator"></select>
</div>
</div>
</div>
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
<div class="form-group">
<div class="col-xs-12">
<label class="control-label" for="name">From <span class="danger">*</span></label>
</div>
<div class="col-xs-12 date">
<div id="timeform1" class="input-append date">
<input data-format="hh:mm:ss" type="text" class="form-control" ng-disabled="!attend" ng-model="from2">
<span class="add-on" >
<i data-time-icon="icon-time"id="icon1" data-date-icon="icon-calendar" ng-show="attend">
</i>
</span>
</div>
</div>
</div>
</div>
<div class="col-lg-3 col-md-3 col-sm-6 col-xs-6">
<div class="form-group">
<div class="col-xs-12">
<label class="control-label" for="name">To <span class="danger">*</span></label>
</div>
<div class="col-xs-12 date">
<div id="timeto1" class="input-append date">
<input data-format="hh:mm:ss" type="text" class="form-control" ng-disabled="!attend" ng-model="to2">
<span class="add-on">
<i data-time-icon="icon-time" data-date-icon="icon-calendar" ng-show="attend">
</i>
</span>
</div>
</div>
</div>
</div>
Angular js
$scope.checkattendance = function () {
if ($scope.attend == true) {
$('#timeform1').datetimepicker({
pickTime: true, pickDate: false
});
$('#timeto1').datetimepicker({
pickTime: true, pickDate: false
});
}
else {
$scope.opinname = '';
$scope.from2 = '';
$scope.to2 = '';
$scope.apply();
}
}
why ng-model=from2 and ng-model=to2 are not binded and clear the data
any help , thanks in advance
One problem is that your current checkattendance function is not changing the attend boolean, it needs to toggle the state from true to false or false to true each time the checkbox is changed, one easy modification is to modify the function and add $scope.attend =!$scope.attend; either at the start or the end of the function. Something like below:
$scope.checkattendance = function () {
$scope.attend =!$scope.attend;
if ($scope.attend == true) {
$('#timeform1').datetimepicker({
pickTime: true, pickDate: false
});
$('#timeto1').datetimepicker({
pickTime: true, pickDate: false
});
}
else {
$scope.opinname = '';
$scope.from2 = '';
$scope.to2 = '';
$scope.apply();
}
}
You should also tie the checkbox's selected state to that boolean something like checked=attend
Written code to save the data and reset the data. In this case data is saving successfully but unable to make reset the form. When i click on pencil icon it turn to floppy disk and remove icon. If i click on floppy disk data is saving but when i click on remove icon data form is not being reset. I tried code this way
//Banking details form validation
$(document).ready(function() {
$('.editBankDetailBtn').click(function() {
if ($('.editBankDetail').is('[readonly]')) { //checks if it is already on readonly mode
$('.editBankDetail').prop('readonly', false); //turns the readonly off
$('.editBankDetailBtn').html(
'<span class="glyphicon glyphicon-floppy-disk"> </span>' +
'<span id="reset-form" class="glyphicon glyphicon-remove"> </span>');
// $('.glyphicon-remove')[0].reset();
} else { //else we do other things
var patt = /^([0-9]{11})|([0-9]{2}-[0-9]{3}-[0-9]{6})$/;
var reg = /^[A-Za-z]{4}[0-9]{6,7}$/;
patt.test('acdbdfdsfsf22-333-666666'); // true
var bname_1 = document.getElementById('name').value;
if (bname_1 == "") {
document.getElementById('name').style.borderColor = "red";
return false;
} else {
document.getElementById('name').style.borderColor = "#cccccc";
}
$('.editBankDetail').prop('readonly', true);
$('.editBankDetailBtn').html(
'<span class="glyphicon glyphicon-pencil"> </span>');
$('.glyphicon-remove').on('click', function() {
$("#reset-form").trigger("reset");
});
}
});
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading" style="background-color: #b3daff;">
<h4 class="panel-title">
<span style="font-weight: 700;">Banking Details</span> <a class="editBankDetailBtn"><span
class="glyphicon glyphicon-pencil"> </span></a>
<a data-toggle="collapse" data-parent="#accordion" href="#collapseFour"> <span class="glyphicon glyphicon-plus" id="pls" style="color: darkred"> </span>
</a>
</h4>
</div>
<div id="collapseFour" class="panel-collapse collapse">
<div class="panel-body">
<div class="col-sm-4 col-md-6">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-8">Bank
Name<span style="color: red;">*</span>
</label>
<div class="col-md-12">
<input type="text" class="form-control editBankDetail" id="bankName" readonly placeholder="Bank Name" />
</div>
</div>
</div>
</div>
<div class="col-sm-4 col-md-6">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-8">Account
Number<span style="color: red;">*</span>
</label>
<div class="col-md-12">
<input type="text" class="form-control editBankDetail" id="accountNumber" readonly placeholder="Account Number" />
</div>
</div>
</div>
</div>
<div class="col-sm-4 col-md-6">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-8">IFSC
CODE<span style="color: red;">*</span>
</label>
<div class="col-md-12">
<input type="text" class="form-control editBankDetail" id="ifscCode" readonly placeholder="IFSC CODE" />
</div>
</div>
</div>
</div>
<div class="col-sm-4 col-md-12">
<div class="row">
<div class="form-group">
<label class="control-label col-sm-12 col-md-8">Bank
Address<span style="color: red;">*</span>
</label>
<div class="col-md-12">
<textarea class="form-control editBankDetail" id="branchAddress" placeholder="Bank Address" readonly> </textarea>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!----Ends second column-------->
</div>
</div>
<!----Ends accordion column-------->
</div>
You have several things
You need to reset a form, not an icon like you do now
PLEASE have a toggleClass on the bankName - it is not name, but bankName in your code
You need to delegate - something like this - the element that gets the event handler has to be static in the page and exist at the time of delegation, here $('.editBankDetailBtn')
$('.editBankDetailBtn').on('click', '.glyphicon-remove', function() {
$("#myForm")[0].reset()
});
Your click will not work on the ones created dynamically. Add below code
$(document).on('click', '.glyphicon-remove', function() {
// Put one alert or console to check that you here
$("#YOU_FORM_ID")[0].reset(); //
});
Using Bootstrap 4.
I have four text inputs, if any of the text inputs contain any values, i'd like to add a class to a button.
When the button is clicked, I would like to clear the input values, and remove the class from the button.
I have half of it working (clicking button successfully clears all inputs).
My code is below;
$(document).ready(function() {
$("#filterRecords input").on("keyup change", function() {
$("#filterRecords input").each(function() {
var element = $(this);
if (element.val().length > 0) {
$('#resetFilter').addClass('btn-outline-primary');
}
});
});
$('#resetFilter').click(function() {
$('input[type=text]').val('').change();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row filterRecords">
<div class="input-group col-xs-6 col-sm-6 col-md-3 mb-3">
<input type="text" id="searchName" class="form-control" placeholder="Search Name">
</div>
<div class="input-group col-sm-6 col-md-3 mb-3">
<input type="text" id="searchLang" class="form-control" placeholder="Search Language">
</div>
<div class="input-group col-sm-6 col-md-3 mb-3">
<input type="text" id="yearMin" class="form-control start" placeholder="Search Start Year">
</div>
<div class="input-group col-sm-6 col-md-3 mb-3">
<input type="text" id="yearMax" class="form-control end" placeholder="Search End Year">
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-md-auto">
<button class="btn btn-sm btn-default" type="button" id="resetFilter">Reset Filters</button>
<hr>
</div>
</div>
Fiddle link.
Any help would be appreciated.
Firstly, filterRecords is a class, not an id, so your selector is incorrect.
Aside from that, the issue with your logic is that it only ever add the class when the input values change. You also need to have some logic to remove it when no input has a value entered.
You can do that by using toggleClass() along with a boolean based on the number of filled inputs, like this:
$(document).ready(function() {
var $inputs = $(".filterRecords input");
$inputs.on("input", function() {
var $filled = $inputs.filter(function() { return this.value.trim().length > 0; });
$('#resetFilter').toggleClass('btn-outline-primary', $filled.length > 0);
});
$('#resetFilter').click(function() {
$inputs.val('').trigger('input');
});
});
.btn-outline-primary {
color: #C00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row filterRecords">
<div class="input-group col-xs-6 col-sm-6 col-md-3 mb-3">
<input type="text" id="searchName" class="form-control" placeholder="Search Name">
</div>
<div class="input-group col-sm-6 col-md-3 mb-3">
<input type="text" id="searchLang" class="form-control" placeholder="Search Language">
</div>
<div class="input-group col-sm-6 col-md-3 mb-3">
<input type="text" id="yearMin" class="form-control start" placeholder="Search Start Year">
</div>
<div class="input-group col-sm-6 col-md-3 mb-3">
<input type="text" id="yearMax" class="form-control end" placeholder="Search End Year">
</div>
</div>
<div class="row justify-content-md-center">
<div class="col-md-auto">
<button class="btn btn-sm btn-default" type="button" id="resetFilter">Reset Filters</button>
<hr>
</div>
</div>
Also note the use of input over the combination of keyup change.
Like this
$(document).ready(function() {
$("#filterRecords input").on("keyup change", function() {
$("#filterRecords input").each(function() {
var element = $(this);
if (element.val().length > 0) {
$('#resetFilter').addClass('btn-outline-primary');
}
});
});
$('#resetFilter').click(function() {
$("#filterRecords**")[0].reset();
$(this).removeClass('btn-outline-primary');
});
});
I'm relatively new to JS and HTML and was following this tutorial ( https://www.youtube.com/watch?v=iaeCSh7YJDM&t=422s ) in order to turn a select box and input box into a dynamic form field in order to add as many of them as needed with an add button. The add button works perfectly, though after implementing the same code as in the video, the remove button does not function and I can't quite figure out why. I've gone back and rewatched and cross checked the videos code and mine though can't seem to see what I'm missing. Any help would be greatly appreciated. Below is the section of code I have.
HTML
<div class="form-group row" id = "addF" >
<label class="col-sm-3 col-lg-3 col-md-3 form-control-label">
Label
</label>
<div class="col-sm-4 col-lg-4 col-md-4">
<select class="form-control" id="xxxx" name="yyyyy" required>
<option class="placeholder" selected disabled value="" style="display:none;">Select Fact</option>
</select>
</div>
<div class="col-sm-3 col-lg-3 col-md-3">
<input type="text" class="form-control" id=vvvv" name="zzzz" required>
</div>
<div class="col-sm-1 col-lg-1 col-md-1">
<input type="button" id="add_fact()" onClick="addFact()" value="+">
</div>
</div>
JS
<script type="text/javascript">
var i =1;
function addFact(){
i++;
var div = document.createElement('div');
div.innerHTML = '<label class="col-sm-3 col-lg-3 col-md-3 form-control-label">Label '+i+'</label><div class="col-sm-4 col-lg-4 col-md-4"> <select class="form-control" id="xxxx'+i+'" name="yyyy_'+i+'" required><option class="placeholder" selected disabled value="" style="display:none;">Select Fact</option></select></div><div class="col-sm-3 col-lg-3 col-md-3"> <input type="text" class="form-control" id="vvvv" name="zzzz_'+i+'" required></div><div class="col-sm-1 col-lg-1 col-md-1"><input type="button" id="add_fact()" onClick="addFact()" value="+"></div><div class="col-sm-1 col-lg-1 col-md-1"><input type="button" value="-" onClick="removeFact(this)"></div>';
document.getElementById('addF').appendChild(div);
function removeFact(div) {
document.getElementById('addF').removeChild(div.parentNode);
i--;
}
</script>
In the "removeFact" function you are not receiving the div element; as you are calling it with "this" as parameter, you receive the button element, so to fix it, you must call the function like this
onClick="removeFact(this.parentNode)"
or change your function this way
function removeFact(button) {
document.getElementById('addF').removeChild(button.parentNode.parentNode);
i--;
}
You have to go one level deeper.
Try this :
<script type="text/javascript">
var i =1;
function addFact(){
i++;
var div = document.createElement('div');
div.innerHTML = '<label class="col-sm-3 col-lg-3 col-md-3 form-control-label">Label '+i+'</label><div class="col-sm-4 col-lg-4 col-md-4"> <select class="form-control" id="xxxx'+i+'" name="yyyy_'+i+'" required><option class="placeholder" selected disabled value="" style="display:none;">Select Fact</option></select></div><div class="col-sm-3 col-lg-3 col-md-3"> <input type="text" class="form-control" id="vvvv" name="zzzz_'+i+'" required></div><div class="col-sm-1 col-lg-1 col-md-1"><input type="button" id="add_fact()" onClick="addFact()" value="+"></div><div class="col-sm-1 col-lg-1 col-md-1"><input type="button" value="-" onClick="removeFact(this)"></div>';
document.getElementById('addF').appendChild(div);
}
function removeFact(div) {
document.getElementById('addF').removeChild(div.parentNode.parentNode);
i--;
}
</script>
I add a form using AJAX in a Php page now I add anther form within that form which is created using AJAX but it is not working.
This is the parent page.
<div class="col-xs-12 mg-top-30 text-left" id="studentstatus">
<div class="col-sm-1 hidden-xs"></div>
<div class="col-sm-2">
<label for="" class="control-label">Are you a?</label>
</div>
<div class="col-sm-5">
<label class="radio-inline">
<input type="radio" name="studentstatus" value="fresh">Freshman</label>
<label class="radio-inline mg-top-5">
<input type="radio" name="studentstatus" value="compart">Reappeared</label>
</div>
</div>
<div id="adddata"></div>`
JQuery to working with AJAX is the following for adding First form:
$(function () {
$('#studentstatus input:radio').change(
function () {
var index = this.value;
$.get(
"add_freshman_form_in_maprevios.php", {
studentstatus: index
},
function (data) {
$("#adddata").html(data);
}
);
}
);
});
add_freshman_form_in_maprevios.php page HTML code is:
$output='<div class="col-xs-12 mg-top-10 text-left">
<div class="col-sm-1 hidden-xs"></div>
<div class="col-sm-2">
<label for="" class="control-label">Roll No.</label>
</div>
<div class="col-sm-2">
<input type="number" class="btn-block input-sm" placeholder="Previous roll no.">
</div>
</div>
<div class="col-xs-12 mg-top-10 text-left">
<div class="col-sm-1 hidden-xs"></div>
<div class="col-sm-3">
<label for="" class="control-label">Write down the names of failed papers:</label>
</div>
</div>
<div class="col-xs-12 mg-top-10 text-left">
<div class="col-sm-1 hidden-xs"></div>
<div class="col-sm-2">
<input type="text" class="btn-block input-sm" placeholder="Failed Paper name...">
</div>
</div>
<div class="col-xs-12 text-left">
<div class="col-sm-1 hidden-xs"></div>
<button class="mg-left-15 color addanother"> <i class="fa fa-plus-circle " > <label for="">Add another</label></i></button>
<div id="compartpaper"></div>
</div>';
echo $output;
It is working very well but when I want another textbox in this form using AJAX than it is not working. I write JQuery code for this purpose into the main page.
$('.addanother').click(function (e) {
e.preventDefault();
$.get(
"add_compart_form_in_previous_paper.php", {
username: $("#username").val()
},
function (data) {
$("#compartpaper").append(data);
}
);
});
The Form which I want to add in this page is mean :
<?php
$output='<div class="col-sm-2">
<input type="text" class="btn-block input-sm" placeholder="Failed Paper name...">
</div>';
echo $output;
?>
You're referring to an element that does not exist when the page is loaded , it is why not enter on the click event. Try this instead.
$("#adddata").on("click", ".addanother", function(){
//your code
});