How to set radio buttons values based on dropdown selection? - javascript

I want to set radio buttons values based on drop-down selection,Lets assume i have three values in drop-down(A,B and C) , If A or B is selected i want to set radio button default value to Summary and if C is selected i want set value to Detailed. Also when A & B is selected i want to make it non-editable..
Please help this is first time i am using radios with AngularJS.
main.html
<div class="row">
<div class="form-group col-md-6 fieldHeight">
<label for="cycleName" class="col-md-6 required">Scope Type :</label>
<div class="col-md-6">
<select kendo-drop-down-list k-data-text-field="'text'"
k-option-label="'Select'" k-data-value-field="'id'"
k-data-source="assessmentTypeOptions" name="assessmentType"
required ng-model="riskAssessmentDTO.scopeType" id="assessmentType"
maxlength="256" ng-change="assessmentType()"></select>
<p class="text-danger"
ng-show="addAssessment.assessmentType.$touched && addAssessment.assessmentType.$error.required">Assessment
Type is required</p>
</div>
</div>
<div class="form-group col-md-6 fieldHeight">
<label for="assessmentType" class="col-md-5 required">Assessment Type :</label>
<label class="radio-inline"><input type="radio"
name="summary" id="summary" ng-value="'summary'"
ng-model="riskAssessmentDTO.erhFlag" ng-disabled="disableAssessmentType" >Summary </label>
<label class="radio-inline"><input type="radio"
name="detail" id="detail" ng-value="'N'"
ng-model="riskAssessmentDTO.erhFlag" ng-disabled="disableAssessmentType">Detailed</label>
<p class="text-danger"
ng-show="addAssessment.includeERHFlag.$touched && addAssessment.includeERHFlag.$error.required">Assessment
Name is required</p>
</div>
</div>
main.js
$scope.assessmentType = function() {
$scope.riskAssessmentDTO.assessmentName = '';
$scope.riskAssessmentDTO.erhFlag = 'Y';
$scope.showRefineERH = false;
if ($scope.riskAssessmentDTO.scopeType === 'RA_GEO_LOCAT') {
$scope.disableAssessmentType = true;
$scope.riskAssessmentDTO.erhFlag = 'summary';
} else if ($scope.riskAssessmentDTO.scopeType === 'RA_LEGAL_ENTITY') {
$scope.disableAssessmentType = true;
$scope.riskAssessmentDTO.erhFlag = 'summary';
} else if ($scope.riskAssessmentDTO.scopeType === 'RA_BUS_UNIT') {
$scope.disableAssessmentType = false;
$scope.riskAssessmentDTO.erhFlag = 'detailed';
}
};

Use ng-disabled in Radio buttons and use a scope variable as $scope.selectedIndex to set it as false or true
<input type="radio" ng-disabled="selectedInderx==0">
and set $scope.selectedIndex in the ng-change function in Select by passing $index from html

Related

How to check/uncheck 3 secondary checkboxes according to 1 principal checkbox (19times)?

I have 19 cards of 4 checkboxes: 1 main checkbox (date) and 3 secondary checkboxes (options for that date). I would like the 3 secondary options to be checked when the main one is checked and conversely that they are unchecked when the main one is unchecked.
I would like to use a single function for all 19 cards. However, checkboxes have different ids.
When I click on a main checkbox
I get the id from the main checkbox.
I retrieve the number contained in the id.
I apply it to three values to create the id of 3 secondary checkboxes.
If the main checkbox is checked:
I check the secondary checkboxes.
If the main checkbox is unchecked:
I uncheck the secondary checkboxes.
I tried with "onclick" and "onchange".
function Autocheck(id) {
var clicked_id = id;
var StgNbr = clicked_id.substr(4);
var diner = "Dîner" + StgNbr;
var souper = "Souper" + StgNbr;
var logement = "Logement" + StgNbr;
if (clicked_id.checked = true) {
alert('je suis coché');
var items = document.getElementsByClassName('presence');
for (var i = 0; i < items.length; i++) {
if (items[i].id == diner)
items[i].checked = true;
if (items[i].id == souper)
items[i].checked = true;
if (items[i].id == logement)
items[i].checked = true;
}
} else {
alert('je suis décoché');
var items = document.getElementsByClassName('presence');
for (var i = 0; i < items.length; i++) {
if (items[i].id == diner)
items[i].checked = false;
if (items[i].id == souper)
items[i].checked = false;
if (items[i].id == logement)
items[i].checked = false;
}
}
}
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3">
<div class="card">
<label for="date1"><div class="card-media"><input type="checkbox" id="date1" class="date presence" name="Dates" onclick="Autocheck(this.id)"> Mardi 23/07</div></label>
<div class="card-details">
<input type="checkbox" class="presence" name="Dîner" id="Dîner1">
<label for="Dîner1"> Dîner</label><br>
<input type="checkbox" class="presence" name="Souper" id="Souper1">
<label for="Souper"> Souper</label><br>
<input type="checkbox" class="presence" name="Logement" id="Logement1">
<label for="Logement"> Logement</label><br>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3">
<div class="card">
<label for="date2"><div class="card-media"><input type="checkbox" id="date2" class="date presence" name="Dates" onchange="Autocheck(this.id)"> Mercredi 24/07</div></label>
<div class="card-details">
<input type="checkbox" class="presence" name="Dîner" id="Dîner2">
<label for="Dîner2"> Dîner</label><br>
<input type="checkbox" class="presence" name="Souper" id="Souper2">
<label for="Souper2"> Souper</label><br>
<input type="checkbox" class="presence" name="Logement" id="Logement2">
<label for="Logement2"> Logement</label><br>
</div>
</div>
</div>
My secondary checkboxes are well cheched but they don't uncheck.
Also : my 'test' alert is always saying that the principal checkbox is checked even if I uncheck it.
Thank you for your help.
Here is a click listener and on click of main checkbox we check/uncheck child check boxes. Is this what you are looking for?
const getParentCard = (e, classToMatch) => {
while( e.classList.contains(classToMatch) === false)
{
e = e.parentNode;
}
return e;
};
document.addEventListener('click', (e) => {
if(e.target.matches('input.date')){
getParentCard(e.target,'card').querySelectorAll('input[type="checkbox"]').forEach(chk => {
chk.checked = e.target.checked;
});
}
});
<div class="row">
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3">
<div class="card">
<label for="date1">
<div class="card-media">
<input type="checkbox" id="date1" class="date presence" name="Dates"> Mardi 23/07
</div>
</label>
<div class="card-details">
<input type="checkbox" class="presence" name="Dîner" id="Dîner1">
<label for="Dîner1"> Dîner</label><br>
<input type="checkbox" class="presence" name="Souper" id="Souper1">
<label for="Souper"> Souper</label><br>
<input type="checkbox" class="presence" name="Logement" id="Logement1">
<label for="Logement"> Logement</label><br>
</div>
</div>
</div>
<div class="col-xs-12 col-sm-6 col-md-3 col-lg-3">
<div class="card">
<label for="date2"><div class="card-media"><input type="checkbox" id="date2" class="date presence" name="Dates"> Mercredi 24/07</div></label>
<div class="card-details">
<input type="checkbox" class="presence" name="Dîner" id="Dîner2">
<label for="Dîner2"> Dîner</label><br>
<input type="checkbox" class="presence" name="Souper" id="Souper2">
<label for="Souper2"> Souper</label><br>
<input type="checkbox" class="presence" name="Logement" id="Logement2">
<label for="Logement2"> Logement</label><br>
</div>
</div>
</div>
There are two main problems in your code:
if (clicked_id.checked = true) {
performs an assignment instead of a comparison but more importantly, clicked_id is a string and string values don't have a checked property. You'd have to access the checked property of the actual element , by either passing the element as argument to the function (preferred) or do
var element = document.getElementById(clicked_id);
//...
if (element.checked) {
// ...
}
Having said that, a more flexible approach that works with any number of check boxes without having to update the code is as follows:
Find closest common ancestor
Find all check boxes within that ancestor
Example:
function Autocheck(element) {
var ancestor = element.closest('.card');
if (ancestor) {
Array.from(ancestor.querySelectorAll('.presence')).forEach(function(input) {
input.checked = element.checked;
});
}
}
and use it as
<input type="checkbox" id="date1" class="date presence" name="Dates" onclick="Autocheck(this)">

Bug in JQuery function for checking for required fields in custom dropdowns

I made a JQuery function to check for empty required fields inside a closed custom dropdown.
If a required field is empty inside one of the dropdown and if the dropdown is currently closed I want the dropdown to open and if there are no empty values in the required fields I want the dropdown to close.
The problem is that the required fields aren't accessible if the dropdowns are closed and I tried to fix that problem with this function.
For some reason, it only checks for these input fields if the form is submitted at least once and the required fields are opened at least once.
find(':input[required]') doesn't give any output if the dropdown isn't opened at least once, once u open and close the dropdown the function works.
This is the function:
function dropdown_required() {
var required = 0;
$('#visible_fields').find(':input[required]').each(function () {
if (!this.value) {
for (var i = 1; i < 15; i++) {
$('.form_' + i).find(':input[required]').each(function () {
$(this).prop('required', false);
});
}
required++;
}
});
if (required == 0) {
for (var i = 1; i < 15; i++) {
var empty = 0;
$('.form_' + i).find(':input[required]').each(function ()
{
if(!this.value) {
empty++;
}
});
if (empty !== 0) {
if ($(".arrow_" + i).hasClass("rotate_2")) {
$(".arrow_" + i).addClass("rotate_1").removeClass("rotate_2");
$(".form_" + i).fadeToggle();
}
} else if ($(".arrow_" + i).hasClass("rotate_1")) {
$(".arrow_" + i).addClass("rotate_2").removeClass("rotate_1");
$(".form_" + i).fadeToggle();
}
}
}
}
This is the html:
<form method="POST" autocomplete="off" enctype="multipart/form-data" target="_self"
action="/contacten/leveranciers/iframe{{ ($leverancier == null ? '' : '/' . $leverancier->cot_id) }}">
{{ csrf_field() }}
<div id="visible_fields">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="organisatie">Organisatie</label>
<input type="text" name="organisatie" id="organisatie" blocked=",;()/" hk="a"
value="{{ ($leverancier == null ? old('organisatie') : $leverancier->cot_organisatie) }}"
class="form-control inputblocked">
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="postcode">Postcode</label>
<input type="text" name="postcode" id="postcode" filter="a-zA-Z0-9" maxlength="6"
value="{{ ($leverancier == null ? old('postcode') : $leverancier->cot_postcode) }}"
class="form-control inputfilter filter_postcode">
</div>
</div>
</div>
//all visible input fields outside of the dropdowns
</div>
<label class="toggle_1">Controles<span class="arrow_1 glyphicon glyphicon-menu-left"
aria-hidden="true"></span></label>
<div class="form_1">
<div class="row">
<div class="col-xs-6">
<div class="form-group">
<label for="bkr">BKR</label>
<select name="bkr" class="form-control" required>
<option selected hidden></option>
<option value="10">BKR toetsing open</option>
<option value="11">BKR toetsing accoord</option>
<option value="12">Vrijgesteld van BKR toetsing</option>
</select>
</div>
</div>
<div class="col-xs-6">
<div class="form-group">
<label for="bkr_bestand">BKR bestand</label>
<input type="file" name="bkr_bestand" id="bkr_bestand"
data-default-file=""
class="form-control dropify">
<input type="hidden" name="verwijder_foto" class="verwijder_foto" value="0">
</div>
</div>
</div>
</div>
<div class="form-group">
<input type="hidden" id="input_iframe" name="input_iframe" value="">
<button type="submit" onclick="dropdown_required()"
class="btn btn-primary">Toevoegen </button>
</div>
</form>
</div>
</body>
</html>
Your function checks if your arrow element has the class rotate_2. The code you pasted has neither rotate_1 or rotate_2 and no else block, so the toggle never executes.
Problem demonstration:
// This group has empty mandatory elements
var empty = 1;
$('#validate').click(function() {
if (empty !== 0) {
console.log("I have empty elements!");
// From your comments, this might be backwards
if ($(".arrow_1").hasClass("rotate_2")) {
console.log("I'm going to show them");
$(".arrow_1").addClass("rotate_1").removeClass("rotate_2");
$(".form_1").fadeToggle();
}
// This is missing in the code
else {
console.log("I wasn't invited to the party");
}
// -------
} else if ($(".arrow_1").hasClass("rotate_1")) {
console.log("I'm out, I don't have empty elements...");
$(".arrow_1").addClass("rotate_2").removeClass("rotate_1");
$(".form_1").fadeToggle();
}
});
$('#simulate').click(function() {
// Simulates manually opening and closing
// In short, add rotate_2 class as if it's been toggled
$('.arrow_1').addClass('rotate_2');
console.log("Toggled manually");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label class="toggle_1">Controles<span class="arrow_1 glyphicon glyphicon-menu-left"
aria-hidden="true"></span></label>
<div class="form_1">
<div>Some form elements</div>
</div>
<button id="validate">Validate</button>
<button id="simulate">Simulate</button>

cash denomination calculator

I've created cash denomination calculator in jquery, and it's working fine once you add entry but suppose if you try to change those entries then it's not calculating values as i expected.
Just fill those values and you'll get total of all, but if try to change the value of input box inside div with '.mul_by' class[i.e. the small input box before '=' sign] then it's not calculating the total properly.
And here's the jsFiddle for the same.
$('.mul_by').each(function (i) {
var _this = $(this),
//set default input value to zero inside .mul-by div
setZero = _this.find('.form-control').val(0),
//set default input value to zero inside .mul-val div
setDenominationVal = _this.siblings('.mul_val').find('.form-control').val(0),
//set default input value to zero inside .total div
setTotalVal = $('.total').val(0);
setZero.on('change', function () {
//watch and store input val. inside .mul_by
var getUpdatedVal = _this.find('.form-control').val(),
//get label text
getDenominationVal = parseInt(_this.siblings('label').text()),
//update mul_by div after multiplication
updateDenominationVal = _this.siblings('.mul_val').find('.form-control');
if (getUpdatedVal > 0) {
var vals = updateDenominationVal.val(getUpdatedVal * getDenominationVal);
total = parseInt(setTotalVal.val()) + parseInt(vals.val());
setTotalVal.val(total);
} else {
updateDenominationVal.val(0);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-horizontal">
<div class="form-group">
<label class="control-label col-md-2 col-xs-2" for="batch">2000</label>
<div class="col-md-1 col-xs-4 mul_by">
<span>x </span> <input type="text" class="form-control">
</div>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2 col-xs-2" for="batch">500</label>
<div class="col-md-1 col-xs-4 mul_by">
<span>x </span> <input type="text" class="form-control">
</div>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-2 col-xs-2" for="batch">100</label>
<div class="col-md-1 col-xs-4 mul_by">
<span>x </span> <input type="text" class="form-control">
</div>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control">
</div>
</div>
<div class="form-group">
<hr>
<label class="control-label col-md-2 col-xs-2" for="batch">total:</label>
<div class="col-md-3 col-xs-5 mul_val">
<span style="font-size: 18px;">= </span> <input type="text" class="form-control total">
</div>
</div>
</form>
How do i update total after making changes?
Hope you understand it. Thanks in advance for your help.
Please check this code i get proper result I had made lot of changes at end hope you will get desired result:-
$(document).ready(function () {
$('.mul_by').each(function (i) {
var _this = $(this),
//set default input value to zero inside .mul-by div
setZero = _this.find('.form-control').val(0),
//set default input value to zero inside .mul-val div
setDenominationVal = _this.siblings('.mul_val').find('.form-control').val(0);
//set default input value to zero inside .total div
setTotalVal = $('.total').val(0);
setZero.on('change', function () {
var getcurrentval = $(this).val();
console.log('getcurrentval',getcurrentval)
//watch and store input val. inside .mul_by
var getUpdatedVal = _this.find('.form-control').val(),
//get label text
getDenominationVal = parseInt(_this.siblings('label').text()),
//update mul_by div after multiplication
updateDenominationVal = _this.siblings('.mul_val').find('.form-control');
console.log(getUpdatedVal,getDenominationVal)
var vals = 0,total=0;
if(getUpdatedVal > 0){
if(updateDenominationVal.val()>0){
vals = updateDenominationVal.val(getUpdatedVal * getDenominationVal - updateDenominationVal.val());
total = parseInt(setTotalVal.val()) + parseInt(vals.val()) ;
updateDenominationVal.val(getUpdatedVal * getDenominationVal);
console.log('total',total,'setTotal',setTotalVal.val(),vals.val());
}
else{
vals = updateDenominationVal.val(getUpdatedVal * getDenominationVal);
updateDenominationVal.val(getUpdatedVal * getDenominationVal);
total = parseInt(setTotalVal.val()) + parseInt(vals.val());
}
console.log(vals.val());
setTotalVal.val(total);
} else{
updateDenominationVal.val(0);
}
});
});
});

Jquery filtering based on radio / checkbox states

I have an issue that I cant seem to figure out how to fix.. Im still green on javascript.
I am having this markup:
<div class="area-listing">
<div id="list-filter">
<input type="radio" id="all" name="rr" data-filter="all" checked />
<label for="all"><span></span>Samtliga</label>
<input type="radio" id="student" name="rr" data-filter="student" />
<label for="student"><span></span>Studentboende</label>
<input type="radio" id="construction" name="rr" data-filter="construction" />
<label for="construction"><span></span>Nybyggnation</label>
<input type="checkbox" id="available" name="cc" data-filter="available" />
<label for="available"><span></span>Visa endast lediga lägenheter</label>
</div>
<div class="area col-sm-4"></div>
<div class="area col-sm-4 construction"></div>
<div class="area col-sm-4 available student"></div>
<div class="area col-sm-4 available"></div>
<div class="area col-sm-4 available"></div>
<div class="area col-sm-4 available"></div>
</div>
function areaListing() {
if ($(".area-listing").length) {
var filters = $(".area-listing #list-filter");
var areas = $(".area-listing .area");
areas.show();
var $areas = $('input').on("change", function () {
if (this.id == 'all') {
areas.fadeIn(450);
} else {
var $el = $('.' + this.id).fadeIn(450);
areas.not($el).hide();
}
$areas.removeClass('filtered');
$(this).addClass('filtered');
})
}
}
And with the javascript I am now filtering fine based on the radio buttons.. However I want to add the possibility to trigger another filter on the "checkbox" to filter out "available" elements. However I can't get it to work.. can anyone assist me? Right now it works on the first checkbox click, but doesnt register when untoggling it.
To clarify: When clicking the checkbox the filtering should remain but only show the areas with available. And when untoggled it should show all.
You can store current filters in variables and change them after clicking on radio or checkbox input.
function areaListing() {
if ($('.area-listing').length) {
var filters = $('.area-listing #list-filter');
var areas = $('.area-listing .area');
areas.show();
var currentFilter = 'all';
var showOnlyAvailable = false;
function filterAreas() {
var currentSelector = '.area';
if (currentFilter !== 'all') {
currentSelector += '.' + currentFilter;
}
if (showOnlyAvailable) {
currentSelector += '.available';
}
var $el = $(currentSelector).fadeIn(450);
areas.not($el).hide();
}
$('input[type="radio"]').on('change', function() {
currentFilter = this.id;
filterAreas();
});
$('input[type="checkbox"]').on('change', function() {
showOnlyAvailable = $(this).is(':checked');
filterAreas();
});
}
}
areaListing();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="area-listing">
<div id="list-filter">
<input type="radio" id="all" name="rr" data-filter="all" checked />
<label for="all"><span></span>Samtliga</label>
<input type="radio" id="student" name="rr" data-filter="student" />
<label for="student"><span></span>Studentboende</label>
<input type="radio" id="construction" name="rr" data-filter="construction" />
<label for="construction"><span></span>Nybyggnation</label>
<input type="checkbox" id="available" name="cc" data-filter="available" />
<label for="available"><span></span>Visa endast lediga lägenheter</label>
</div>
<div class="area col-sm-4">a</div>
<div class="area col-sm-4 construction">b</div>
<div class="area col-sm-4 available student">c</div>
<div class="area col-sm-4 available">d</div>
<div class="area col-sm-4 available">e</div>
<div class="area col-sm-4 available">f</div>
</div>
Here's code for the filtering based on both Checkbox AND Radio button. When any of the radio button or checkbox is checked(or checkbox is unchecked), you need to first get the checked status of checkbox. If this checkbox is checked, only areas with .available should be shown and others should be hidden. If this checkbox is unchecked, there is no need to bother about .available elements.
Here are some suggestions:
Wrap the code interacting with DOM in ready
$('.area-listing').length is not needed as it'll always be true provided that code is executed after page load
filters is never used, thus can be removed.
areas.show() is not needed if .area elements are not hidden.
Instead of ID, use data-filter to get the class on which the filter is to be applied.
Fiddle Demo
// When DOM is completely loaded
$(document).ready(function() {
'use strict';
// Cache element references
var $areas = $('.area');
var $checkbox = $('#available');
var $radios = $('#list-filter :radio');
var checkboxFilter = $checkbox.data('filter');
// Bind change event on radio buttons and checkbox
$('#list-filter').on('change', ':radio, :checkbox', function(e) {
// Get the checked status of checkbox
var isCheckboxChecked = $checkbox.is(':checked');
// Get the checked radio button filter
var radio = $radios.filter(':checked').data('filter');
// Create filter based on checked radio button and checkbox state
var filter = isCheckboxChecked ? '.' + radio + '.' + checkboxFilter : '.' + radio;
if (radio === 'all') {
if (isCheckboxChecked) {
// Show only .available
$areas.filter('.' + checkboxFilter).fadeIn(450);
} else {
// Show all
$areas.fadeIn(450);
}
} else {
// Hide those except filtered
$areas.not(filter).hide();
// Show filtered
$areas.filter(filter).fadeIn(450);
}
}).trigger('change'); // To call the handler on page load
});
label {
margin-right: 2px;
}
div.area {
margin: 5px;
color: green;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="area-listing">
<div id="list-filter">
<input type="radio" id="all" name="rr" data-filter="all" checked />
<label for="all"><span></span>Samtliga</label>
<input type="radio" id="student" name="rr" data-filter="student" />
<label for="student"><span></span>Studentboende</label>
<input type="radio" id="construction" name="rr" data-filter="construction" />
<label for="construction"><span></span>Nybyggnation</label>
<input type="checkbox" id="available" name="cc" data-filter="available" />
<label for="available"><span></span>Visa endast lediga lägenheter</label>
</div>
<div class="area col-sm-4">First</div>
<div class="area col-sm-4 construction">Second</div>
<div class="area col-sm-4 available student">Third</div>
<div class="area col-sm-4 available">Fourth</div>
<div class="area col-sm-4 available">Fifth</div>
<div class="area col-sm-4 available">Sixth</div>
</div>
I think i know what you want to do, first of all, doing the checks from radios or checkboxes is a little bit weird for normal usage, i think you need to use a "filter" button, so i added one to filter every option selected.
This is the JS code:
//Launch the filter with a button
$("#list-filter input[type='button']").click(function(){
//Get the element
var input = $("#list-filter input[type='radio']:checked").attr("data-filter");
var check = $("#list-filter input[type='checkbox']");
//Check for available only
if(check.is(":checked")){
if(input=="all"){ //Show all available
$(".area-listing .area").css("display","none");
$(".area-listing .area.available").css("display","block");
}
else{ //Show only available in the desired area
$(".area-listing .area").css("display","none");
$(".area-listing .area.available."+input).css("display","block");
}
}
else //If not available is checked
{
if(input=="all"){ //Show all
$(".area-listing .area").css("display","block");
}
else{ //Show only the desired area
$(".area-listing .area").css("display","none");
$(".area-listing .area."+input).css("display","block");
}
}
});
This is the full test (i added a CSS to hide all areas by default, and the button to filter all options)
https://jsfiddle.net/psyzc79w/
Tell me if this way is useful for you.

Pass array of checkboxes with ajax along with other inputs

Currently I have been using ajax to post to a few methods in my code igniter installation. I now have a form that has a checkbox array with other inputs and am having problems passing the value into post. Currently it returns the last value of the the last checkbox even if it's not checked.
.js
$('.flagPost').on('submit', function() {
var that = $(this), url = that.attr('action'), type = that.attr('method'), data = {};
that.find('[name]').each(function(index, value) {
var that = $(this), name = that.attr('name'), value = that.val();
data[name] = value;
});
$.ajax({
url : url,
type : type,
data : data,
success : function(response) {
$('#flagSuccess').empty().append(response).fadeIn('slow').delay(3000).fadeOut(800);
}
});
return false;
});
.html
<div class="form-group">
<label for="email" class="col-sm-4 control-label">Email</label>
<div class="col-sm-8">
<input type="email" class="form-control input-sm" name="email" id="email" placeholder="Email Address" value="<?php echo set_value('email');?>">
</div>
<span class="help-block"></span>
</div>
<div class="form-group">
<label class="control-label col-sm-4">Issues/Problems</label>
<div class="col-sm-8">
<label class="checkbox" for="problems-0">
<input type="checkbox" name="problem[]" id="problems-0" value="Adult Content">
Adult Content
</label>
<label class="checkbox" for="problems-1">
<input type="checkbox" name="problem[]" id="problems-1" value="Spam">
Spam
</label>
<label class="checkbox" for="problems-2">
<input type="checkbox" name="problem[]" id="problems-2" value="Non-existent">
Non-existent
</label>
<label class="checkbox" for="problems-3">
<input type="checkbox" name="problem[]" id="problems-3" value="Language">
Language
</label>
<label class="checkbox" for="problems-4">
<input type="checkbox" name="problem[]" id="problems-4" value="Other">
Other
</label>
</div>
<span class="help-block"></span>
</div>
<!-- Textarea -->
jQuery has a serialize method for grabbing all the data from a form (following the normal rules for what controls count as successful)
data = that.serialize()
Since the checkboxes have the same value for the name attribute they are overwriting the same property on the data object.
that.find('[name]').each(function(index, value) {
var that = $(this), name = that.attr('name'), value = that.val();
data[name] = value; //This overwrites the property
});
Look at using jQuery's serialize function instead of building your own object to pass.
JS fiddle: http://jsfiddle.net/7Aysb/

Categories

Resources