Filtering through multiple times in javascript - javascript

So, I have an object named products that has 3 attributes:
var products = [
{"name":"product1","size":"large","color":"blue","gender":"male"},
{"name":"product2","size":"small","color":"pink","gender":"female"},
{"name":"product3","size":"large","color":"green","gender":"male"},
{"name":"product4","size":"large","color":"yellow","gender":"female"},
{"name":"product5","size":"medium","color":"blue","gender":"female"},
{"name":"product6","size":"large","color":"green","gender":"male"},
{"name":"product7","size":"small","color":"yellow","gender":"male"},
{"name":"product8","size":"medium","color":"red","gender":"female"},
{"name":"product9","size":"large","color":"blue","gender":"male"},
{"name":"product10","size":"small","color":"red","gender":"female"}
];
So, if I have 3 select boxes for size, color, and gender, how would I filter these 3 to get the product name?
I'm trying to use .filter in javascript. I know how to use it in non-associative arrays. But, what about associative arrays? how do you use them?

var color = document.getElementById("color").value;
var gender = document.getElementById("gender").value;
var size = document.getElementById("size").value;
var matched = products.filter(function(e) {
return (e.color == color && e.gender == gender && e.size == size);
}).map(function(e) { return e.name; });

I wrote a JSfiddle to go with this answer. Check it out here: http://jsfiddle.net/THEtheChad/XjGPt/
JQuery
$('input').change(function(){
var names = filter();
});
function filter(){
var selected = {
size: $('#size') .val(),
color: $('#color') .val(),
gender: $('#gender').val()
};
var matches = products.filter(function(product){
return product.size == selected.size &&
product.color == selected.color &&
product.gender == selected.gender;
});
return matches.map(function(product){ return product.name });
}
Vanilla JS
var d = document;
var inputs = d.getElementsByTagName('input');
// Convert to array
inputs = Array.prototype.slice.call(inputs);
inputs.forEach(function(input){
input.addEventListener('change', function(e){
var names = filter();
});
});
function filter(){
var selected = {
size: d.getElementById('size') .value,
color: d.getElementById('color') .value,
gender: d.getElementById('gender').value
};
var matches = products.filter(function(product){
return product.size == selected.size &&
product.color == selected.color &&
product.gender == selected.gender;
});
return matches.map(function(product){ return product.name });
}

Not as elegant as Barmar's code, I implemented 2 out of the 3 dropboxes and left a bit of work for you as well ;)
<html>
<head>
<script>
var products = [
{"name":"product1","size":"large","color":"blue","gender":"male"},
{"name":"product2","size":"small","color":"pink","gender":"female"},
{"name":"product3","size":"large","color":"green","gender":"male"},
{"name":"product4","size":"large","color":"yellow","gender":"female"},
{"name":"product5","size":"medium","color":"blue","gender":"female"},
{"name":"product6","size":"large","color":"green","gender":"male"},
{"name":"product7","size":"small","color":"yellow","gender":"male"},
{"name":"product8","size":"medium","color":"red","gender":"female"},
{"name":"product9","size":"large","color":"blue","gender":"male"},
{"name":"product10","size":"small","color":"red","gender":"female"}
];
function checkValidOption(){
var color_chosen = document.getElementById("color").value;
var size_chosen = document.getElementById("size").value;
var result = "";
//only if both options were chosen
if (color_chosen !== "empty" && size_chosen != "empty"){
for(var i=0; i<products.length; i++){
if(products[i].size == size_chosen && products[i].color == color_chosen){
result = products[i].name;
break;
}
}
document.getElementById('result').innerHTML = result;
}
}
</script>
</head>
<body>
<div id="wrapper">
<select id="size" name="size" onchange="checkValidOption();">
<option value="empty"/>
<option value="small">small</option>
<option value="medium">medium</option>
<option value="large">large</option>
</select>
<select id="color" name="color" onchange="checkValidOption();">
<option value="empty"/>
<option value="red">red</option>
<option value="yellow">yellow</option>
<option value="blue">blue</option>
<option value="green">green</option>
<option value="pink">pink</option>
</select>
</div><!--wrapper-->
<div id="result"></div>
</body>
</html>

Related

get multiple var in a function by find()

I am trying to create a calculation with two selected option and input. Like when you select 'a' and 'd' then input=1 it give result 75. I wrote a jquery code but it doesn't work . I can't find any error on console .Please check it below :
$(window).load(function(){
function doStuff() {
var uone= $("#ud").children(":selected").attr("id") == 'a';
var utwo= $("#ud").children(":selected").attr("id") == 'b';
var uthree= $("#ud").children(":selected").attr("id") == 'c';
var bone= $("#bt").children(":selected").attr("id") == 'd';
var btwo= $("#bt").children(":selected").attr("id") == 'e';
var getvalue;
if ($(uone).find(bone)) {
getvalue = 75;
}
if ($(uone).find(btwo)) {
getvalue = 70;
}
if ($(utwo).find(bone)) {
getvalue = 81;
}
if ($(uthree).find(bone)) {
getvalue = 79;
}
var shw = $('#inputamount').val();
var total = getvalue * shw ;
$("#totalop").html(total);
}
$("#inputamount").on('keyup', doStuff);
$("#ud").on('change', doStuff);
$("#bt").on('change', doStuff);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<select name="sucompn" id="ud">
<option id="a">a</option>
<option id="b">b</option>
<option id="c">c</option>
</select>
<select name="ducompn" id="bt">
<option id="d">d</option>
<option id="e">e</option>
</select>
<input autocomplete="off" name="inputamount" id="inputamount" value="" type="text">
<span id="totalop"></span>
don't use id use value for the options
<select name="sucompn" id="ud">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
<select name="ducompn" id="bt">
<option value="d">d</option>
<option value="e">e</option>
</select>
then you can get the values like
var selectedUd = $("#ud").val();
var selectedBt = $("#bt").val();
then you can do:
var uone = selectedUd== 'a';
var utwo = selectedUd == 'b';
var uthree = selectedUd == 'c';
var bone =selectedBt == 'd';
var btwo =selectedBt== 'e';
then (I don't really know what you wanted to do here ) but you could do things like
var getValue;
if(uone && bone) getvALUE =75;
else if(uone && btwo) getValue = 70;
else if(utwo && bone) getValue = 81;
...here rthe rest of posibilities
var shw = $('#inputamount').val();
var total = getvalue * shw;
$("#totalop").html(total);
Here is the Plunker - Sample
You have defined var getValue;, but use in code another variable getvalue = 75;(getValue and getvalue are not the same). Probably you have undefined variable and this problem usually yields no console info.

How do I remove old options in Jquery when parent select box is changed?

I have 3 chained select boxes using jquery and json.
Depending on first 2 values I filter third one my code actually works but the problem is when I change values of first 2 select boxes third select recieves new datas while keeping old ones.
I've tried to empty my array but it didn't work.
$(document).ready(function() {
var json = JSON.parse(jsonString);
var makesArray = [];
var selectedyear;
var selectedcourse;
var $yearDropDown = $("#DropDown_Year");
var $course_type = $("#course_type");
$yearDropDown.change(function() {
selectedyear = this.value;
//filter based on selected year.
});
$course_type.change(function(){
selectedcourse = this.value;
makesArray = jQuery.grep(json, function(course, i) {
return course.course_type == selectedcourse && course.year_code == selectedyear;
})
var selectBox = document.getElementById('DropDown_Make');
for(var i = 0, l = makesArray.length; i < l; i++){
var option = makesArray[i];
selectBox.options.add( new Option(option.course_code, option.course_code, option.course_code) );
}
makesArray= []; //makesArray.empty();
});
});
<div id="DrpDwn">
Year:
<select id="DropDown_Year">
<option>Yıl</option>
<option value="15">2015-2016</option>
<option value="16">2016-2017</option>
</select>
<select class="form-control" id="course_type" name="course_type" required>
<option value="" selected> Choose</option>
<option value="Yos">YÖS</option>
<option value="SatMatGeo">SAT (MAT)</option>
<option value="SatCriRea">SAT (ENG)</option>
<option value="TomerABC">TÖMER (ABC)</option>
<option value="TomerAB">TÖMER (AB)</option>
<option value="TomerBC">TÖMER (BC)</option>
<option value="TomerA1A2">TÖMER (A)</option>
<option value="TomerB1B2">TÖMER (B)</option>
<option value="TomerC1C2">TÖMER (C)</option>
</select>
Make:
<select id="DropDown_Make">
<option>None</option>
</select>
</div>
and this is JSFIDDLE
https://jsfiddle.net/rw7cb8c5/25/
Make DropDown_Make empty using selectBox.innerHTML = "" in $course_type.change() like following.
$course_type.change(function () {
selectedcourse = this.value;
makesArray = jQuery.grep(json, function (course, i) {
return course.course_type == selectedcourse && course.year_code == selectedyear;
})
var selectBox = document.getElementById('DropDown_Make');
selectBox.innerHTML = ""; //added this line
for (var i = 0, l = makesArray.length; i < l; i++) {
var option = makesArray[i];
selectBox.options.add(new Option(option.course_code, option.course_code, option.course_code));
}
makesArray.empty();
});
UPDATED FIDDLE

change de select option value name

I have this html code i want change the value from 0 to usa and from 1 to australia and from 3 to canada i need de name of this value in mysqol database.
thanks
html
<form method="post" id="countriesForm" name="countriesForm" enctype="application/x-www-form-urlencoded">
<select id="select1" name="select1">
<option value="0">USA</option>
<option value="1">AUSTRALIA</option>
<option value="2">CANADA</option>
</select>
</form>
<img id="flags" height="30" width="50" border="0" name="flags"></img>
js
(function(){
var imageArray = new Array("http://www.agem.org/images/flags/united_states.png", "http://www.agem.org/images/flags/australia.png", "http://www.agem.org/images/flags/canada.png");
var altArray = new Array("USA", "AUSTRALIA", "CANADA");
document.getElementById('select1').onchange = function() {
var e = document.getElementById('select1');
var index = e.options[e.selectedIndex].value;
var targetImg = document.getElementById('flags');
targetImg.src = imageArray[index];
targetImg.alt = altArray[index];
};
})();
You can just do this: <option value="usa">USA</option> or you can check in your onSubmit-Listener what the number is and then change the value which should be submitted:
function submit() {
var select1 = document.getElementById('select1');
var index = select1.value;
var country = 'usa';
if(index == 0) {
country = 'usa';
} else if(index == 1) {
country = 'australia';
} else if(index == 2) {
country = 'cananda';
}
}

Count Unique Selection from Multiple Dropdown

I'm new to jquery, I'm working on a survey form and I have multiple dropdown menus for different questions but they all have the same dropdown value. Supposed I have:
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
And other different dropdowns with different id's. What is the best way to count how many has selected Yes, No and N/A/ ? Thanks
you can do it simple this way
$('select').change(function() {
// get all selects
var allSelects = $('select');
// set values count by type
var yes = 0;
var no = 0;
// for each select increase count
$.each(allSelects, function(i, s) {
// increase count
if($(s).val() == 'Yes') { yes++; }
if($(s).val() == 'No') { no++; }
});
// update count values summary
$('.cnt-yes').text(yes);
$('.cnt-no').text(no);
});
DEMO
Try this — https://jsfiddle.net/sergdenisov/h8sLxw6y/2/:
var count = {};
count.empty = $('select option:selected[value=""]').length;
count.yes = $('select option:selected[value="Yes"]').length;
count.no = $('select option:selected[value="No"]').length;
count.nA = $('select option:selected[value="N/A"]').length;
console.log(count);
My way to do it would be :
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
Check the console (or replace with alert).
With your code, it would be something like that (assuming you want to check on a button click event) :
<select name="Forms[AgentIsPitch]" id="Forms_AgentIsPitch">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<select name="Forms[MandatoryOptIsStated]" id="Forms_MandatoryOptIsStated">
<option value="">Choose One</option>
<option value="Yes">Yes</option>
<option value="No">No</option>
<option value="N/A">N/A</option>
</select>
<button class="btn btn-primary" id="countYes"></button>
<script type="text/javascript">
$('#countYes').on('click', function(){
var optionsYes = $("option[value$='Yes']:selected");
var optionsNo = $("option[value$='No']:selected");
var optionsNA = $("option[value$='N/A']:selected");
console.log('number of yes selected = ' + optionsYes .length);
console.log('number of no selected = ' + optionsNo .length);
console.log('number of N/A selected = ' + optionsNA .length);
});
</script>
You can check at another event, I choosed a button click just for example.
There is likely a cleaner way to do this, but this will get the job done (assuming there is a button click to trigger things):
$("#theButton").on('click', function() {
var totalSelect = 0;
var totalYes = 0;
var totalNo = 0;
var totalNA = 0;
$("select").each(function(){
totalSelect++;
if ($(this).val() == "Yes") { totalYes++; }
if ($(this).val() == "No") { totalNo++; }
if ($(this).val() == "N/A") { totalNA++; }
});
});
Hope this helps the cause.
In common you can use change event:
var results = {};
$('select').on('change', function() {
var val = $(this).val();
results[val] = (results[val] || 0) + 1;
});
DEMO
If you want count for each type of select:
$('select').on('change', function() {
var val = $(this).val();
var name = $(this).attr('name');
if (!results[name]) {
results[name] = {};
}
results[name][val] = (results[name][val] || 0) + 1;
});
DEMO
In the results will be something like this:
{
"Forms[AgentIsPitch]": {
"Yes": 1,
"No": 2,
"N/A": 3
},
"Forms[MandatoryOptIsStated]": {
"No": 5,
"N/A": 13
},
}
UPD: for counting current choice:
$('select').on('change', function() {
var results = {};
$('select').each(function() {
var val = $(this).val();
if (val) {
results[val] = (results[val] || 0) + 1;
}
})
console.log(results);
});
DEMO

Creating multiple Select options from an Object

Im stack on creating multiple select options
I have an Object with multi objects inside and want create select options in condition of the previous select option , i provide js fiddle for better understanding .
my objectif is
first select category ----(then)---> select sex -----(then)---> select kind---(then)-->then select size
by this order from that Object.
i could do the select sex and it works but not kind and size.
this is my html
<form name="myform">
<div>
<select name="category_group" id="category_group" >
<option value="0">choose category</option>
<option value='401' > clothes </option>
<option value='403' > shoes </option>
</select>
</div>
<br>
<div>
<select id="clothing_sex" name="clothing_sex" onChange="showclothesKind(this.value,this.form.clothing_kind)">
<option value="0">choose Type»</option>
</select>
<select id="clothing_kind" name="clothing_kind">
<option value="0">choose clothes</option>
</select>
<select id="clothing_size" name="clothing_size">
<option value="0">choose size</option>
</select>
</div>
</form>
and js in the fiddle.
much appreciate your help.
This was kind of fun to play around with. Thanks for posting. I used the following:
var optionTemplate = "<option class='newOption'>sampleText</option>";
$(document).ready(function() {
var removeFromNextSelects = function(firstSelector) {
var selNum = sels.indexOf(firstSelector);
for (var i = selNum; i < sels.length; i++)
{
$(sels[i]).find('.option').remove();
}
};
var populateNextSelect = function(neededObject, targetSelector) {
removeFromNextSelects(targetSelector);
for (var key in neededObject)
{
var name;
neededObject[key].name ? name = neededObject[key].name : name = neededObject[key];
$(targetSelector).append(optionTemplate);
$('.newOption').val(key).html(name).removeClass('newOption').addClass('option');
}
};
var obj1 = {}, obj2 = {}, obj3 = {};
var sels = ["#clothing_sex", "#clothing_kind", "#clothing_size"];
$('#category_group').change(function() {
if ($(this).val() == 0)
{
removeFromNextSelects(sels[0]);
return;
}
obj1 = {};
var selection = $(this).val();
obj1 = clothes[selection];
populateNextSelect(obj1, sels[0]);
});
$('#clothing_sex').change(function() {
if ($(this).val() == 0)
{
removeFromNextSelects(sels[1]);
return;
}
obj2 = {};
var selection = $(this).val();
obj2 = obj1[selection].types;
populateNextSelect(obj2, sels[1]);
});
$('#clothing_kind').change(function() {
if ($(this).val() == 0)
{
removeFromNextSelects(sels[2]);
return;
}
obj3 = {};
var selection = $(this).val();
var arr = obj2[selection].sizes;
for (var i = 0; i < arr.length; i++)
{
obj3[Object.keys(arr[i])[0]] = arr[i][Object.keys(arr[i])[0]];
}
populateNextSelect(obj3, sels[2]);
});
});
Here's the fiddle

Categories

Resources