How to create an array in jquery when checkbox is clicked? - javascript

I have a checkbox for brands and a check box for prices. Now if a user clicks on the check box I want an array of brand_ids and an array of prices.
<div class="left-filters__inner--block">
<ul class="filter-data filter-data-brands" id="brands_list">
#foreach(App\Brand::all() as $brand)
<li>
<label for="{{$brand->name}}" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect">
<input type="checkbox" name="brands[]" id="{{$brand->name}}" class="mdl-checkbox__input" data-value="{{$brand->id}}">
<span class="mdl-checkbox__label">{{$brand->name}}</span>
</label>
</li>
#endforeach
</ul>
</div>
price view with checkbox
<div class="left-filters__inner--block">
<ul class="filter-data filter-data-price" id="price_list">
<li>
<label for="less-20" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect">
<input type="checkbox" id="less-20" class="mdl-checkbox__input" name="price" data-value="0,20">
<span class="mdl-checkbox__label">Less than 20</span>
</label>
</li>
<li>
<label for="21-50" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect">
<input type="checkbox" id="21-50" class="mdl-checkbox__input" name="price" data-value="21,50">
<span class="mdl-checkbox__label">21 - 50</span>
</label>
</li>
<li>
<label for="51-100" class="mdl-checkbox mdl-js-checkbox mdl-js-ripple-effect">
<input type="checkbox" id="51-100" class="mdl-checkbox__input" name="price" data-value="51,100">
<span class="mdl-checkbox__label">51 - 100</span>
</label>
</li>
Now when user clicks on the checkbox a particular brand or price I want an array which looks like this.
Array
(
[brand_id] => Array
(
[0] => 1
[1] => 2
[2] => 3
)
[price] => Array
(
[0] => 0,1000
[1] => 1000,2000
)
)
I want to achieve this using jquery. Please assists

https://jsfiddle.net/2moqx8da/
$("input:checkbox").click(function() {
var brandids=[], prices=[];
$("input[name='brands']:checked").each(function() {
brandids.push($(this).val())
});
$("input[name='price']:checked").each(function() {
prices.push($(this).val())
});
$('#output').text(JSON.stringify([brandids, prices]));
});

Related

Get total number of input tags in a div element

new to js and trying to get a total number of input tags in a div element then display the total.
Thanks for the help and sorry if this is a repeat question.
<div class="card-body">
<span>0</span> / <span id="total-inputs"></span>
<ul>
<li>
<input type="checkbox" id="input-1" class="sum" value="1" >
<label for="input-1">
Input 1
</label>
</li>
<li>
<input type="checkbox" id="input-2" class="sum" value="1" >
<label for="input-2">
Input 2
</label>
</li>
</ul>
</div>
const element = document.getElementsByClassName("card-body");
const nodes = element.getElementsByTagName("input");
document.getElementById("total-inputs").innerHTML = nodes.length;
Getting this error:
TypeError: element.getElementsByTagName is not a function
const element = document.getElementsByClassName("card-body") should be const element = document.getElementsByClassName("card-body")[0] since getElementsByClassName() returns an array:
const element = document.getElementsByClassName("card-body")[0];
const nodes = element.getElementsByTagName("input");
document.getElementById("total-inputs").innerHTML = nodes.length;
<div class="card-body">
<span>0</span> / <span id="total-inputs"></span>
<ul>
<li>
<input type="checkbox" id="input-1" class="sum" value="1" >
<label for="input-1">
Input 1
</label>
</li>
<li>
<input type="checkbox" id="input-2" class="sum" value="1" >
<label for="input-2">
Input 2
</label>
</li>
</ul>
</div>
You can use the new function querySelector and querySelectorAll.
Example:
var div = document.querySelector('div.card-body');
var inputs = div.querySelectorAll('input');
var inputLenth = inputs.length;
console.log(inputLenth);
Reference
Document.querySelector()

Display/hide divs after selection of multiple radio buttons

I am currently working on a filter that displays products categories through Radio Button selection:
<div class="round" id="r-group">x
<label for="r2" class="label-filter">
<input type="radio" id="r1" name="club-selection" value="club-selection">
<span class="label-text">The Club Selection</span>
</label>
<label for="r2" class="label-filter">
<input type="radio" id="r2" name="upholstery" value="upholstery">
<span class="label-text">All Upholstery</span>
</label>
<label for="r3" class="label-filter">
<input type="radio" id="r3" name="casegoods" value="casegoods">
<span class="label-text">All Casegoods</span>
</label>
<label for="r3" class="label-filter">
<input type="radio" id="r4" name="tables" value="tables">
<span class="label-text">All Tables</span>
</label>
<label for="r3" class="label-filter">
<input type="radio" id="r5" name="lighting" value="lighting">
<span class="label-text">All Lighting</span>
</label>
</div>
I want to be able show each category as I select the radio buttons. For example: If I select All Casegoods, I want to only show the div with data-category="casegoods". If I select Tables and Lighting I want to show the div with data-category="tables" and data-category="lighting". These are the basic structure of the divs per category:
<div class="product" data-category="club-selection">
<h4>The Club Selection</h4>
</div>
<div class="product" data-category="upholstery">
<h4>Upholstery</h4>
</div>
<div class="product" data-category="casegoods">
<h4>Casegoods</h4>
</div>
<div class="product" data-category="tables">
<h4>All Tables</h4>
</div>
<div class="product" data-category="lighting">
<h4>Lighting</h4>
</div>
So far, I am able to store the value of the selected radio buttons into an array (selectedValues), but I am not sure what to do next to be able to display only the divs of the categories selected.This is the code that store the values:
$(function(){
var items = $("[data-category]");//get all the elements that has data-categories attribute
items.show(); //show all of the elements we found above
$("input[type=radio]").on("change",function(ev){ //bind onchange event
var selectedValues = []; //this array will hold all of the current categories
$("input:checked").each(function(idx, checkedRadio){//get all of the input radio buttons that are checked and add the value of each of them to the selectedValues array we created above
selectedValues.push($(checkedRadio).val().toLowerCase());
//THIS IS WHERE I´M STUCK. What do I do with the values stored in the array?
});
});
});
EDIT:fixed the ids on the inputs.
You can do something like this:
var elems = $("[data-category]").filter(function() {
return selectedValues.indexOf($(this).data("category")) > -1;
});
elems.show();
I believe you want to use checkbox and not radio, since you cant deselect them again. Else you have to use the same name so you cant select more than one.
Also please note that many of your inputs have the same id, ID should always be unique.
Demo
$(function() {
var items = $("[data-category]"); //get all the elements that has data-categories attribute
items.show(); //show all of the elements we found above
$("input[type=checkbox]").on("change", function(ev) { //bind onchange event
$("[data-category]").hide()
var selectedValues = []; //this array will hold all of the current categories
$("input:checked").each(function(idx, checkedRadio) { //get all of the input radio buttons that are checked and add the value of each of them to the selectedValues array we created above
selectedValues.push($(checkedRadio).val().toLowerCase());
});
var elems = $("[data-category]").filter(function() {
return selectedValues.indexOf($(this).data("category")) > -1;
});
elems.show();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="round" id="r-group">
<label for="r2" class="label-filter">
<input type="checkbox" id="r2" name="club-selection" value="club-selection">
<span class="label-text">The Club Selection</span>
</label>
<label for="r2" class="label-filter">
<input type="checkbox" id="r2" name="upholstery" value="upholstery">
<span class="label-text">All Upholstery</span>
</label>
<label for="r3" class="label-filter">
<input type="checkbox" id="r3" name="casegoods" value="casegoods">
<span class="label-text">All Casegoods</span>
</label>
<label for="r3" class="label-filter">
<input type="checkbox" id="r3" name="tables" value="tables">
<span class="label-text">All Tables</span>
</label>
<label for="r3" class="label-filter">
<input type="checkbox" id="r3" name="lighting" value="lighting">
<span class="label-text">All Lighting</span>
</label>
</div>
<div class="product" data-category="club-selection">
<h4>The Club Selection</h4>
</div>
<div class="product" data-category="upholstery">
<h4>Upholstery</h4>
</div>
<div class="product" data-category="casegoods">
<h4>Casegoods</h4>
</div>
<div class="product" data-category="tables">
<h4>All Tables</h4>
</div>
<div class="product" data-category="lighting">
<h4>Lighting</h4>
</div>

Jquery - Get value of checkbox inside li on span click

There is list inside ul li like below:
<ul class="AllLayer">
<li>
<fieldset id="layer0">
<label class="checkbox" for="visible0">
<input id="visible0" class="visible" type="checkbox" /> OSM
</label>
<span class="edit fa fa-pencil-square">eidt</span>
</fieldset>
</li>
<li>
<fieldset id="layer1">
<label class="checkbox" for="visible1">
<input id="visible1" class="visible" type="checkbox" value="osm2" /> osm2
</label>
<span class="edit fa fa-pencil-square">eidt</span>
</fieldset>
</li>
</ul>
When user click on span I must get value of checkbox before this span.
I wrote below code but it return undefined.
$("span.edit").on('click', function () {
var value= (this).parent().siblings("input[type='checkbox']").attr("value");
alert(value);
});
Could you help me please?
You need to use find() method to get the checkbox inside its parent.
Additionally, you can use :checkbox selector to get checkbox element which would be better than the attribute equals selector and the value can be access using val() method.
$("span.edit").on('click', function() {
var value = $(this).parent().find(":checkbox").val();
// or $(this).sblings().find(":checkbox").val()
// or $(this).prev().find(":checkbox").val()
alert(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="AllLayer">
<li>
<fieldset id="layer0">
<label class="checkbox" for="visible0">
<input id="visible0" class="visible" type="checkbox" /> OSM
</label>
<span class="edit fa fa-pencil-square">eidt</span>
</fieldset>
</li>
<li>
<fieldset id="layer1">
<label class="checkbox" for="visible1">
<input id="visible1" class="visible" type="checkbox" value="osm2" /> osm2
</label>
<span class="edit fa fa-pencil-square">eidt</span>
</fieldset>
</li>
</ul>

jquery to iterate through list items with nested inputs

I have inputs nested inside of anchors nested inside of list items. I'd like to use jquery to iterate through the list items, and if an item was selected display the values in a text field. I'm close, I'm down to the input control, but the "if (checked)" statement is not working.
Can somebody please tell me what I'm doing wrong? :(
function ddDistrictChanged() {
var txt = "nothing selected";
var $inp = $('#ddDistrict').find('input');
$inp.each(function (index) {
$('#txtHere').text($(this).children('li'));
if ($(this).checked) {
txt = txt + ', ' + $(this).text();
}
$('#txtHere2').text(txt);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="ddDistrict" class="dropdown-menu">
<li><input name="selCol" type="checkbox" value="1"> District 1 (Porter)</li>
<li><input name="selCol" type="checkbox" value="2"> District 2 (Jones Jr.)</li>
<li><input name="selCol" type="checkbox" value="3"> District 3 (Horne)</li>
<li><input name="selCol" type="checkbox" value="4"> District 4 (Haddaway)</li>
<li><input name="selCol" type="checkbox" value="5"> District 5 (Duncan)</li>
<li><input name="selCol" type="checkbox" value="6"> District 6 (Willner)</li>
<li><input name="selCol" type="checkbox" value="7"> District 7 (Brady)</li>
<li><button type="button" class="btn btn-default btn-sm btn-info center-block" onclick="ddDistrictChanged();">Submit</button></li>
</ul>
<div id="txtHere"></div>
<div id="txtHere2"></div>
Would make it cleaner if you wrapped the text in an element like <span>
<li><a ><input/><span> District 1 (Porter)</span></a></li>
Next can use :checked pseudo selector to select only checked inputs
function ddDistrictChanged() {
var txt = "nothing selected";
var $items = $('#ddDistrict').find('li has(input:checked)');
if ($items.length) {
txt = $items.map(function() {
return $(this).find('span').text()
}).get().join(', ');
}
$('#txtHere2').text(txt);
}
Working JSFiddle DEMO
To start with, lets refactor your HTML to make it a bit easier to interact with when using JavaScript/jQuery. I have opted to use labels with your inputs instead of <a> tags.
<ul class="ddDistrict dropdown-menu">
<li>
<input type="checkbox" id="cbox1" value="1" checked>
<label for="cbox1" class="small underlineText_No">District 1 (Porter)
</label>
</li>
<li>
<input type="checkbox" id="cbox2" value="2">
<label for="cbox2" class="small underlineText_No">District 2 (Jones Jr)
</label>
</li>
<li>
<input type="checkbox" id="cbox3" value="3">
<label for="cbox3" class="small underlineText_No">District 3 (Horne)
</label>
</li>
<li>
<input type="checkbox" id="cbox4" value="4">
<label for="cbox4" class="small underlineText_No">District 4 (Haddaway)
</label>
</li>
<li>
<input type="checkbox" id="cbox5" value="5">
<label for="cbox5" class="small underlineText_No">District 5 (Duncan)
</label>
</li>
<li>
<input type="checkbox" id="cbox6" value="6">
<label for="cbox6" class="small underlineText_No">District 6 (Willner)
</label>
</li>
<li>
<input type="checkbox" id="cbox7" value="7">
<label for="cbox7" class="small underlineText_No">District 7 (Brady)
</label>
</li>
<li>
<button type="button" class="btn btn-default btn-sm btn-info center-block" onclick="ddDistrictChanged();">Submit</button>
</li>
</ul>
<div class="txtHere"></div>
I then created some basic JavaScript/jQuery to check if any checkboxes have been checked on load and update the DOM according to what has been checked, and when they are checked.
var $inputs = $('.ddDistrict input');
var $outputWrapper = $('.txtHere');
// Check for boxes that have already been checked and
// append their labels to the DOM.
$inputs.each(function() {
var currentLabel = $(this).next('label').text();
var currentID = $(this).attr('id');
if (this.checked) {
var outputText = $('<p></p>').addClass(currentID).text(currentLabel);
$outputWrapper.append(outputText);
}
});
// This event handler will watch for any changes to the
// checkboxes and will append the value of their labels
// to the DOM on change.
$inputs.change(function() {
var currentLabel = $(this).next('label').text();
var currentID = $(this).attr('id');
if (this.checked) {
var outputText = $('<p></p>').addClass(currentID).text(currentLabel);
$outputWrapper.append(outputText);
} else {
$('.' + currentID).remove();
}
});
It's all relatively simple stuff and the code can be refactored to make it more DRY, but this should definitely put you in the right direction. Let me know if you have any questions.

Javascript Object to filter json Array

I've got multiple checkboxes in an HTML form. When I click on a button, the checked values are put into an JavaScript object and a filter function is triggered.
this.filterChkbx.on('click', function() {
_this.checkedFilter.push({
filterEl: this.value
});
});
In the filter function I'm pulling a json file.
$.ajax("ajax/search-test-data.json")
.done(function (data){
...
Now I want to show the objects matching the values from the form. That´s what my json looks like:
{
"searchtest" : [
{
"id" : "001",
"section": "Hochschule",
"group": "Professoren",
"location": "Kaiserslautern",
"date": "HS 2015/11",
"description" : "Lorem ipsum dolor sit amet",
"details" : "VZ",
"deadline" : "27.12.2015",
"topic" : "Lorem"
},
{
"id" : "002",
And this is my form:
<form class="filterThisResults" action="ajax/search-test-data.json" method="GET">
<ul class="filter-list">
<button type="reset">Filter löschen</button>
<div class="search-filter-section">
<li>
<h2>Bereich</h2>
</li>
<li>
<input class="filterCheckbx" type="checkbox" name="section" value="Hochschule">
<label for="check1">Hochschule</label>
</li>
<li>
<input class="filterCheckbx" type="checkbox" name="section" value="Angewandte Ingenierwissenschaften">
<label for="check2">Angewandte Ingenierwissenschaften</label>
</li>
<li>
<input class="filterCheckbx" type="checkbox" name="section" value="Bauen & Gestalten">
<label for="check3">Bauen & Gestalten</label>
</li>
<li>
<input class="filterCheckbx" type="checkbox" name="section" value="BWL">
<label for="check4">BWL</label>
</li>
<li>
<input class="filterCheckbx" type="checkbox" name="section" value="Informatik">
<label for="check5">Informatik</label>
</li>
<li>
<input class="filterCheckbx" type="checkbox" name="section" value="Logistik">
<label for="check6">Logistik</label>
</li>
</div>
<div class="search-filter-group">
<li>
<h2>Gruppen</h2>
</li>
<li>
<input class="filterCheckbx" type="checkbox" name="group" value="Professoren">
<label for="check1">Professoren</label>
</li>
<li>
<input class="filterCheckbx" type="checkbox" name="group" value="Studenten">
<label for="check2">Studenten</label>
</li>
<li>
<input class="filterCheckbx" type="checkbox" name="group" value="Angestellte">
<label for="check3">Angestellte</label>
</li>
</div>
<div class="search-filter-location">
<li>
<h2>Standort</h2>
</li>
<li>
<input class="filterCheckbx" type="checkbox" name="location" value="Kaiserslautern">
<label for="check1">Kaiserslautern</label>
</li>
<li>
<input class="filterCheckbx" type="checkbox" name="location" value="Pirmasens">
<label for="check2">Pirmasens</label>
</li>
<li>
<input class="filterCheckbx" type="checkbox" name="location" value="Zweibrücken">
<label for="check3">Zweibrücken</label>
</li>
</div>
<div class="search-filter-topic">
<li>
<h2>Thema</h2>
</li>
<li>
<select class="filterCheckbx" id="topic" name="topic" size="3">
<option value="Lorem">Lorem</option>
<option value="Ipsum">Ipsum</option>
<option value="Dolor">Dolor</option>
</select>
</li>
</div>
<li>
<button class="submit-filter" type="submit">Ergebnisse anzeigen</button>
<li>
</ul>
</form>
What´s the way to go through the json and check which items are true. When more than one item in a form-section is selected, the results are enlarged.
Array.prototype.filter():
creates a new array with all elements that pass the test implemented by the provided function
Array.prototype.some():
tests whether some element in the array passes the test implemented by the provided function
.done(function(data) {
var elementsFoundInData = data.searchtest.filter(function(test) {
return checkedFilter.some(function(flt) {
return test.section === flt.filterEL;
});
});
// show found elements...
})
This is more like pseudo code as you probably would have to adjust the variables (checkFilter, data) a little bit depending on their scopes/types.
Instead push values in object, why should you not try with 'serialize' object property of jQuery.
Try this to store all form data in single string and then use filer and some method to match the values.
function showValues() {
var str = $( "form" ).serialize();
console.log(str);
}
$('[type=reset]').on("click",function(e){
showValues();
event.preventDefault();
})

Categories