YUI 3: Set Value to Multiple Select - javascript

I using YUI 3, but I have a question about YUI usage.
I have a select tag with some option tags:
YUI().use( "node", "event", "cssbutton", function(Y){
Y.one('body').addClass('yui3-skin-sam');
Y.one('#btnSel2').on('click',function(){
Y.one('#mySelect').set('value', '5');
});
});
<select id="mySelect" size="10" multiple="true">
<option value="1">Apple</option>
<option value="2">Mango</option>
<option value="3">PineApple</option>
<option value="4">Orange</option>
<option value="5">Peach</option>
</select>
<button id="btnSel2" class="yui3-button">Set Selected</button>
The above method just cover one value, can i set multiple value from array or string with comma delimited?

If you check yui3/build/dom-base/dom-base.js line 202 you will see this feature is not implemented:
if (options && options.length) {
// TODO: implement multipe select
if (node.multiple) {
} else if (node.selectedIndex > -1) {
val = Y_DOM.getValue(options[node.selectedIndex]);
}
}
Here is how we implemented this feature:
YUI().use( "node", "event", "cssbutton", function(Y){
Y.one('body').addClass('yui3-skin-sam');
Y.DOM.VALUE_GETTERS.select = function(node) {
var val = node.value,
options = node.options;
if (options && options.length) {
if (node.multiple) {
val = [];
for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) {
if (option.selected) val.push(Y.DOM.getValue(option));
};
} else if (node.selectedIndex > -1) {
val = Y.DOM.getValue(options[node.selectedIndex]);
}
}
return val;
};
Y.DOM.VALUE_SETTERS.select = function(node, val) {
if (node.multiple && !Y.Lang.isArray(val)) val = [val]; // Allow to set value by single value for multiple selects
for (var i = 0, options = node.getElementsByTagName('option'), option; option = options[i++];) {
if ((node.multiple && val.indexOf(Y.DOM.getValue(option)) > -1) || (!node.multiple && Y.DOM.getValue(option) === val)) {
option.selected = true;
//Y_DOM.setAttribute(option, 'selected', 'selected');
}
}
};
Y.one('#btnSel2').on('click',function(){
Y.one('#mySelect').set('value', ['1', '5']);
});
});
<script src="http://yui.yahooapis.com/3.18.1/build/yui/yui-min.js"></script>
<select id="mySelect" size="10" multiple="true">
<option value="1">Apple</option>
<option value="2">Mango</option>
<option value="3">PineApple</option>
<option value="4">Orange</option>
<option value="5">Peach</option>
</select>
<button id="btnSel2" class="yui3-button">Set Selected</button>

Related

multiple select remove disable button if select is not empty

I'm working with multiple select, and i want to remove the attribute disabled button if all select has value, however the "technician" has sub item which is required and other phase don't have sub.
I wan't to remove disable attribute if all select(NO SUB) has value, and select(with sub) has value.
Here's my code:
const type = document.getElementById("empType");
const phase = document.getElementById("phase");
const subPhase = document.getElementById("subPhase");
type.addEventListener("change", appendPhase);
function appendPhase(){
$("#phase").empty();
var option = '';
if(type.value == 1){
option += '<option value="0">SELECT</option><option value="1">Trainee</option><option value="2">Acting</option><option value="3">Competency</option>'
}
if(type.value == 2){
option += '<option value="0">SELECT</option><option value="1">Phase 1</option><option value="2">Phase 2</option>'
}
if(type.value == 0){
$(subPhase).attr("hidden", true);
option += '<option value="0">SELECT</option>'
}
$(phase).append(option);
$(subPhase).attr("hidden", true);
}
phase.addEventListener("change", showIfTech);
function showIfTech() {
if(type.value == 2){
$(subPhase).attr("hidden", false);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="empType">
<option value="0">SELECT</option>
<option value="1">LINE LEADER</option>
<option value="2">TECHNICIAN</option>
</select>
<select id="phase">
<option value="0">SELECT</option>
</select>
<select id="subPhase" hidden>
<option value="0">SELECT</option>
<option value="1">COMMON</option>
<option value="2">ELECTRICAL</option>
<option value="3">MECHANICAL</option>
</select>
<br>
<br>
<button disabled>CHECK ME</button>
First, you need to add id attribute to button to use it later.
Second, use event listner change (using event delegation) to listen all select boxes change where it is not hidden with selector select:not([hidden]). And then test that all select boxes are selected where value is not 0.
Here is the code.
const type = document.getElementById("empType");
const phase = document.getElementById("phase");
const subPhase = document.getElementById("subPhase");
type.addEventListener("change", appendPhase);
function appendPhase() {
$("#phase").empty();
var option = '';
if (type.value == 1) {
option += '<option value="0">SELECT</option><option value="1">Trainee</option><option value="2">Acting</option><option value="3">Competency</option>'
}
if (type.value == 2) {
option += '<option value="0">SELECT</option><option value="1">Phase 1</option><option value="2">Phase 2</option>'
}
if (type.value == 0) {
$(subPhase).attr("hidden", true);
option += '<option value="0">SELECT</option>'
}
$(phase).append(option);
$(subPhase).attr("hidden", true);
}
phase.addEventListener("change", showIfTech);
function showIfTech() {
if (type.value == 2) {
$(subPhase).attr("hidden", false);
}
}
document.addEventListener('change', isAllSelected);
function isAllSelected() {
let allSelected = [];
const allSelectBoxes = document.querySelectorAll('select:not([hidden])');
allSelectBoxes.forEach((item) => {
if (item.value != '0') {
allSelected.push(item.value);
}
});
const checkMeButton = document.getElementById('check-me-button');
if (allSelected.length === allSelectBoxes.length) {
checkMeButton.disabled = false;
} else {
checkMeButton.disabled = true;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="empType">
<option value="0">SELECT</option>
<option value="1">LINE LEADER</option>
<option value="2">TECHNICIAN</option>
</select>
<select id="phase">
<option value="0">SELECT</option>
</select>
<select id="subPhase" hidden>
<option value="0">SELECT</option>
<option value="1">COMMON</option>
<option value="2">ELECTRICAL</option>
<option value="3">MECHANICAL</option>
</select>
<br>
<br>
<button id="check-me-button" disabled>CHECK ME</button>

disabling options in a dropdown based on another dropdown

I am trying to disable/remove options in a dropdown, based on the selection of other dropdown options.
But the dropdown/selector we have to choose from, has a sub-dropdown list and both main and sub dropdowns are
sharing the same classes and ids but since both are wrapped in different divs with different ids, I have been
trying to access the second selector but couldn't .
Below is the js code that I used for this;
<script type="text/javascript">
document.getElementById("lvl1").querySelector("select").onchange = function()
{
if(this.value=="8"){
var bikeSizes = document.getElementById("pa_size[]");
for ( var i = 1; i <8; i++) {
bikeSizes.options[i].removeAttribute("disabled", "disabled");
}
for ( var i = 8; i < 12; i++) {
bikeSizes.options[i].setAttribute("disabled", "disabled");
}
} else {
var bikeSizes = document.getElementById("pa_size[]");
for ( var i = 1; i < 8; i++) {
bikeSizes.options[i].setAttribute("disabled", "disabled");
}
for ( var i = 8; i < 12; i++) {
bikeSizes.options[i].removeAttribute("disabled", "disabled");
}
}
return false;
};
</script>
The html code of the selector/dropdowns are;
— Select —
Camping
Road Sports
Snow Sports
Water Sports
<div id="lvl1" level="1" style="">
<select data-required="yes" data-type="select" name="product_cat" id="product_cat" class="cat-ajax product_cat wpuf_product_cat_">
<option value="-1">— Select —</option>
<option class="level-0" value="8">Bikes</option>
</select>
<span data-taxonomy="{"required":"yes","name":"product_cat","exclude_type":"child_of","exclude":"camping,road-sports,water-sports","orderby":"name","order":"ASC"}"></span>
</div>
I fixed the quote then put it in an onload function. Also, there is no second argument on a removeAttribute. This worked for me.
<script>
window.onload = function () {
document.getElementById("product_cat").onchange = function () {
if (this.value == "8") {
var bikeSizes = document.getElementById("pa_size[]");
for (var i = 1; i < 8; i++) {
bikeSizes.options[i].removeAttribute("disabled");
}
for (var i = 8; i < 12; i++) {
bikeSizes.options[i].setAttribute("disabled", "disabled");
}
} else {
var bikeSizes = document.getElementById("pa_size[]");
for (var i = 1; i < 8; i++) {
bikeSizes.options[i].setAttribute("disabled", "disabled");
}
for (var i = 8; i < 12; i++) {
bikeSizes.options[i].removeAttribute("disabled");
}
}
return false;
};
}
</script>
<!-- my test html -->
<div id="lvl1" level="1" style="">
<select data-required="yes" data-type="select" name="product_cat" id="product_cat" class="cat-ajax product_cat wpuf_product_cat_">
<option value="-1">— Select —</option>
<option class="level-0" value="8">Bikes</option>
</select>
<span data-taxonomy="{"required":"yes","name":"product_cat","exclude_type":"child_of","exclude":"camping,road-sports,water-sports","orderby":"name","order":"ASC"}"></span>
<select id="pa_size[]">
<option value="-1">--Select--</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
<option value="11">11</option>
<option value="12">12</option>
<option value="13">13</option>
</select>
</div>
Based on what I saw on your website, here is an alternative solution:
<script>
var group1 = [ { value:"33", text:"Small Unisex"},
{ value:"34", text:"Large Unisex"},
{ value:"35", text:"XL Unisex"},
{ value:"36", text:"Small Womens"},
{ value:"37", text:"Medium Womens"},
{ value:"38", text:"Large Womens"},
{ value:"39", text:"XL Womens"}];
var group2 = [{value:"40", text:"Medium"},
{value:"41", text:"Small"},
{ value:"43", text:"XL"},
{ value:"42", text:"Large"}];
window.onload = function() {
document.getElementById("product_cat").onchange = function () {
var bikeSizes = document.getElementById("pa_size[]");
bikeSizes.innerHTML = "";
bikeSizes.appendChild(new Option("--Select--", "-1"));
bikeSizes.disabled = false;
if (this.value == "-1") {
bikeSizes.disabled = true;
}
else if (this.value == "8") {
for (var i = 0; i < group1.length; ++i){
var opt = new Option(group1[i].text, group1[i].value);
bikeSizes.appendChild(opt);
}
} else {
for (var i = 0; i < group2.length; ++i) {
var opt = new Option(group2[i].text, group2[i].value);
bikeSizes.appendChild(opt);
}
}
return false;
};
}
</script>
so is this closer to what you need? This is 3 select boxes where you can only see the second one after the first one has a valid selection. Then you can only see the third one when the second one has a valid choice.
The options available is dependent on its master select box.
you can see it work here http://jsbin.com/nijahoh/edit?html,js,output
<script>
var fakeData = {
group1: [{ value: "group3", text: "3" }, { value: "group4", text: "4" }],
group2: [{ value: "group5", text: "5" }, { value: "group6", text: "6" }],
group3: [{ value: "group7", text: "7" }, { value: "group8", text: "8" }],
group4: [{ value: "group9", text: "9" }, { value: "group10", text: "10" }]
};
$(document).ready(function(){
// first select box change handler
$("#product_cat").on("change", function () {
var val = this.value;
$("#d").val("-1");
setUpSel($("#d"), val);
$("#d").trigger("change");
$("#d").css("display", val=="-1"?"none":"");
});
$("#d").on("change", function () {
var val = this.value;
$("#c").val("-1");
setUpSel($("#c"), val);
$("#c").trigger("change");
$("#c").css("display", val == "-1" ? "none" : "");
});
});
function setUpSel($sel, group) {
$sel.html("<option value='-1'>--Select--</option>");
var selData = fakeData[group];
$.each(selData, function (i, opt) {
$sel.append(new Option(opt.text, opt.value));
});
}
</script>

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

Filtering through multiple times in 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>

Categories

Resources