I have three select elements:
<select id="first">
<option></option>
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
</select>
<select id="second">
<option></option>
<option value="d">d</option>
<option value="e">e</option>
<option value="f">f</option>
</select>
<select id="three">
<option></option>
<option value="g">g</option>
<option value="h">h</option>
<option value="i"></option>
</select>
All three of them must either be empty (first option), or have a value.
So <option></option> <option></option> <option></option> is ok
but not <option value="a">a</option> <option></option> <option></option> kinda thing.
I've tried this, but it isn't working as it doesn't allow all three to be empty and quits on the first case
if($("#first").val() === "" || $("#second").val() === "" || $("#third").val() === ""){
return false;
}
Any help? I would like to do this as short/nice looking as possible
You could
var $selects = $('#first, #second, #three'),
$selected = $selects.filter(function () {
return this.value != ''
});
if ($selected.length != 0 && $selected.length != $selects.length) {
return false;
}
Demo: Fiddle
var first = $("#first").val();
var second = $("#first").val();
var three = $("#first").val();
var isValid = false;
if((first.length>0 && second.length>0 && three.length>0) || (first.length==0 && second.length>== && three.length==0)){
isValid = true;
}
Try this:
if($("#first").find('option').length <=1 || $("#second").find('option').length <=1 || $("#third").find('option').length <=1){
return false;
}
Related
I have list of selectboxs like below.I want to access name of down to up first select box which one has value "a" selected.
when sb3 has selected values = b then if sb2 selected values =a I want o get this one else if sb1 selected values =a i want o get this one
when sb2 has selected values =b then if sb1 selected values =a I want o get this one and like so
I have tryed
console.log( $("[name^='sb'] option[value='a']:selected").closest('select').attr("name") );
or
console.log( $(this).parent().closest( "[name^='sb'] option[value='ana']" ).attr("name") );
sample select lists;
<select name="sb1" >
<option value="a"></option>
<option value="b"></option>
</select>
<select name="sb2" >
<option value="a"></option>
<option value="b"></option>
</select>
<select name="sb3" >
<option value="a"></option>
<option value="b"></option>
</select>
edit anaother examle;
i want to get closest item prior to selested item.
sb45=a
sb46=a
sb47=b --> this give me sb46
sb48=b --> this give me sb46
sb49=a
sb50=b --> this give me sb49
thanks for help.
You have to make a recurssive function wich iterate throw prev element and search for select with value == a otherwise no one selected .
function getRecursivePrevName($node) {
$sb = $($node).prev("[name^='sb']");
if($sb.length) {
if($sb.val()=="a") return $sb.attr("name")
else return getRecursivePrevName($sb);
}
else return null;
}
Attaching the change handler will show wich sb* is selected ( priority from top to bottom )
See below snippet :
$("[name^='sb']").on("change", function() {
if($(this).val() !== 'a') {
var value = getRecursivePrevName($(this));
console.log(value);
if(value != null )
$("#selected").html("select sb is <span style='color:red'>" + value + "</span>");
else $("#selected").html("no select has value a");
}else {
console.log($(this).attr("name"));
$("#selected").html("select sb is <span style='color:red'>" + $(this).attr("name") + "</span>");
}
});
function getRecursivePrevName($node) {
$sb = $($node).prev("[name^='sb']");
if($sb.length) {
if($sb.val()=="a") return $sb.attr("name")
else return getRecursivePrevName($sb);
}
else return null;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<select name="sb1">
<option></option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select name="sb2">
<option></option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select name="sb3">
<option></option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select name="sb4">
<option></option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select name="sb5">
<option></option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<select name="sb6">
<option></option>
<option value="a">a</option>
<option value="b">b</option>
</select>
<br><br>
<div id="selected">
<div>
if I have html like this.
<select multiple="" class="form-control" id="catalogsearch_specification2">
<option value="B-3-7">aaa</option>
<option value="B-3-7">bbb</option>
<option value="B-3-7">ccc</option>
<option value="B-3-7">ddd</option>
</select>
How to check if all value in select option are the same with javascript ?
Use Set object to check if each of the option elements has the same value property. If so - use Array#forEach to apply selected prop on each of them.
let parent = document.getElementById('catalogsearch_specification2'),
values = Array.from(parent.children).map(v => v.value);
[...new Set(values)].length == 1 ? Array.from(parent.children).forEach(v => v.selected = true) : null;
<select multiple="" class="form-control" id="catalogsearch_specification2">
<option value="B-3-7">aaa</option>
<option value="B-3-7">bbb</option>
<option value="B-3-7">ccc</option>
<option value="B-3-7">ddd</option>
</select>
You can do:
var isSame = true,
prev = '';
$('#catalogsearch_specification2 > option').each(function() {
if (prev && prev !== this.value) {
isSame = false;
return;
}
prev = this.value;
});
console.log(isSame);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="" class="form-control" id="catalogsearch_specification2">
<option value="B-3-7">aaa</option>
<option value="B-3-7">bbb</option>
<option value="B-3-7">ccc</option>
<option value="B-3-7">ddd</option>
</select>
This snippet will help you understand how to retrieve values from child nodes.
var obj = {};
var i = 0
$("#catalogsearch_specification2 option").each(function() {
//You can write you logic here.
if(!obj.hasOwnProperty(this.value)) {
obj[this.value] = {"value" : this.value, "duplicate" : 1};
} else {
obj[this.value].duplicate = (obj[this.value].duplicate) + 1;
}
});
console.log(JSON.stringify(obj));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple="" class="form-control" id="catalogsearch_specification2">
<option value="B-3-7">aaa</option>
<option value="B-3-7">bbb</option>
<option value="B-3-7">ccc</option>
<option value="B-3-7">ddd</option>
</select>
Here I'm taking all the child option element of id "catalogsearch_specification2".
There are a numerous way you can check. Here is a solution. Take the first option value and count total no of option with that value. And again count the total option value. If the count are same then all option values are same otherwise not.
$(function(){
var firstValue = $('#catalogsearch_specification2').find("option:first-child").val();
if($('#catalogsearch_specification2 option[value="'+firstValue+'"]').length == $('#catalogsearch_specification2 option').length){
console.log("All values are same");
}else{
console.log("All values are not same");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<select multiple="" class="form-control" id="catalogsearch_specification2">
<option value="B-3-7">aaa</option>
<option value="B-3-7">bbb</option>
<option value="B-3-7">ccc</option>
<option value="B-3-1">ddd</option>
</select>
I Have html select form like this:
<label>Num:</label>
<select id="id_num">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value=''>all</option>
</select>
<label>Choices:</label>
<select id="id_choices">
<option value='car'>car</option>
<option value='bike'>bike</option>
<option value='house'>house</option>
<option value='money'>money</option>
<option value='plane'>plane</option>
<option value='wife'>wife</option>
</select>
In my case I need to make it so that if I choose "1" at the first select form (# id_num), then the next select form (#id_choices) should only show "car" and "bike" options, and if I choose "2", #id_choices should only show "house" and "money", and also the rest.. But if i select "all", then every options on #id_choices should be shown.
How to solve that condition by using jQuery?
You can use jQuery's $.inArray() to filter your options, and make them display: none; depending upon the occurence of the item in the array,
Please have a look on the code below:
$(function() {
$('#id_num').on('change', function(e) {
if ($(this).val() == 1) {
var arr = ['car', 'bike'];
$('#id_choices option').each(function(i) {
if ($.inArray($(this).attr('value'), arr) == -1) {
$(this).css('display', 'none');
} else {
$(this).css('display', 'inline-block');
}
});
} else if ($(this).val() == 2) {
var arr = ['house', 'money'];
$('#id_choices option').each(function(i) {
if ($.inArray($(this).attr('value'), arr) == -1) {
$(this).css('display', 'none');
} else {
$(this).css('display', 'inline-block');
}
});
} else if ($(this).val() == 3) {
var arr = ['plane', 'wife'];
$('#id_choices option').each(function(i) {
if ($.inArray($(this).attr('value'), arr) == -1) {
$(this).css('display', 'none');
} else {
$(this).css('display', 'inline-block');
}
});
} else {
$('#id_choices option').each(function(i) {
$(this).css('display', 'inline-block');
});
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Num:</label>
<select id="id_num">
<option disabled selected>Select</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value=''>all</option>
</select>
<label>Choices:</label>
<select id="id_choices">
<option value='car'>car</option>
<option value='bike'>bike</option>
<option value='house' >house</option>
<option value='money' >money</option>
<option value='plane' >plane</option>
<option value='wife' >wife</option>
</select>
Hope this helps!
You can run a function once when the page loads and then every time #id_num changes, such that all the visible #id_choices options are removed (using remove()), and then only the relevant options are re-added to #id_choices (using append()) to replace them.
Working Example:
$(document).ready(function(){
var car = '<option value="car">car</option>';
var bike = '<option value="bike">bike</option>';
var house = '<option value="house">house</option>';
var money = '<option value="money">money</option>';
var plane = '<option value="plane">plane</option>';
var wife = '<option value="wife">wife</option>';
function options1() {
$('#id_choices').append(car);
$('#id_choices').append(bike);
}
function options2() {
$('#id_choices').append(house);
$('#id_choices').append(money);
}
function options3() {
$('#id_choices').append(plane);
$('#id_choices').append(wife);
}
function displayOptions() {
$('#id_choices option').remove();
switch ($('#id_num option:selected' ).text()) {
case('1') : options1(); break;
case('2') : options2(); break;
case('3') : options3(); break;
case('all') : options1(); options2(); options3(); break;
}
}
$('#id_num').change(function(){displayOptions();});
displayOptions();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Num:</label>
<select id="id_num">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value=''>all</option>
</select>
<label>Choices:</label>
<select id="id_choices">
<option value='car'>car</option>
<option value='bike'>bike</option>
<option value='house'>house</option>
<option value='money'>money</option>
<option value='plane'>plane</option>
<option value='wife'>wife</option>
</select>
For the sake of completeness, here is the same approach as above, but this time in native javascript, so you can compare and contrast with the jQuery above:
var numbers = document.getElementById('id_num');
var choices = document.getElementById('id_choices');
function displayOptions() {
var optionSet1 = ['car', 'bike'];
var optionSet2 = ['house', 'money'];
var optionSet3 = ['plane', 'wife'];
var oldOptions = choices.getElementsByTagName('option');
var selected = numbers.options[numbers.selectedIndex].text;
while (oldOptions.length > 0) {
choices.removeChild(oldOptions[0]);
}
switch (selected) {
case('1') : var optionSet = optionSet1; break;
case('2') : optionSet = optionSet2; break;
case('3') : optionSet = optionSet3; break;
case('all') : optionSet = optionSet1.concat(optionSet2).concat(optionSet3); break;
}
for (var i = 0; i < optionSet.length; i++) {
var option = document.createElement('option');
option.setAttribute('value',optionSet[i]);
option.textContent = optionSet[i];
choices.appendChild(option);
}
}
numbers.addEventListener('change',displayOptions,false);
window.addEventListener('load',displayOptions,false);
<label>Num:</label>
<select id="id_num">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value=''>all</option>
</select>
<label>Choices:</label>
<select id="id_choices">
<option value='car'>car</option>
<option value='bike'>bike</option>
<option value='house'>house</option>
<option value='money'>money</option>
<option value='plane'>plane</option>
<option value='wife'>wife</option>
</select>
Add the attribute display with a value of none using .prop() instead of using disabled attribute (like in Saumya's answer) in case you want them completely invisible instead of just disabled/grayed-out
there may be a better way, however this does work.. you can also add hide/display classes to any other elements
$(document).ready(function () { $('#id_num').on('change', change) });
function change() {
$('#id_choices > option').hide();
$($(this).find(':selected').attr('clssval')).show();
}
.sel{display:none;}
.num1{display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Num:</label>
<select id="id_num">
<option value='1' clssval=".num1">1</option>
<option value='2' clssval=".num2">2</option>
<option value='3' clssval=".num3">3</option>
<option value='' clssval=".num1,.num2,.num3">all</option>
</select>
<label>Choices:</label>
<select id="id_choices">
<option value='car' class="sel num1">car</option>
<option value='bike' class="sel num1">bike</option>
<option value='house' class="sel num2">house</option>
<option value='money' class="sel num2">money</option>
<option value='plane' class="sel num3">plane</option>
<option value='wife' class="sel num3">wife</option>
</select>
So basically I am trying to make a page where the user can select options from two drop down menus, when the second drop down menu has been completed and both have options in them I want it to trigger some javascript that takes those values and then returns text depending on the output.
E.g. a user selects xbox and comfort trade, the price is returned as £5, or maybe they select playstation and comfort trade, the price is returned as £2.50, or maybe they want pc and player auction the price is only £0.99.
HTML
<select id="platform" name="platform">
<option select value=""></option>
<option value="xbox">Xbox</option>
<option value="playstation">PlayStation</option>
<option value="pc">PC</option>
</select><br>
<p>Select Method:</p>
<select id="method" name="method" onChange="price()">
<option selected value=""></option>
<option value="comfortTrade">Comfort Trade</option>
<option value="playerAuction">Player Auction</option>
</select><br>
<h3 id="price"></h3>
Javascript
function price() {
if ($(document.getElementById("platform")) === "xbox" && $(document.getElementById("method")) === "comfortTrade") {
document.getElementById("price").innerHTML = "£5";
} else if ($(document.getElementById("platform")) === "playstation" && $(document.getElementById("method")) === "comfortTrade") {
document.getElementById("price").innerHTML = "£2.50";
}
}
I'm quite new to Javascript but I had a go at doing this, I also have spent the past hour or so trying to search for tutorials on this but nothing got it to work.
Try with this javascript function:
function price() {
if (document.getElementById("platform").value == "xbox" && document.getElementById("method").value == "comfortTrade") {
document.getElementById("price").innerHTML = "£5";
} else if (document.getElementById("platform").value == "playstation" && document.getElementById("method").value == "comfortTrade") {
document.getElementById("price").innerHTML = "£2.50";
}
}
A couple things need to be updated in the existing code to get this to work:
1) onchange has no capital letters, and needs to be added to "platform" <select> as well
2) no need for $ here, can simply use document.getElementById
3) after selecting the element in step 2, will need to get the value of the select by accessing the property .value on the element.
Fixed code:
<div id="app">
<select id="platform" name="platform" onchange="price()">
<option select value=""></option>
<option value="xbox">Xbox</option>
<option value="playstation">PlayStation</option>
<option value="pc">PC</option>
</select><br>
<p>Select Method:</p>
<select id="method" name="method" onchange="price()">
<option selected value=""></option>
<option value="comfortTrade">Comfort Trade</option>
<option value="playerAuction">Player Auction</option>
</select><br>
<h3 id="price"></h3>
</div>
<script>
function price() {
if(document.getElementById("platform").value === "xbox" && document.getElementById("method").value === "comfortTrade") {
document.getElementById("price").innerHTML = "£5";
} else if(document.getElementById("platform").value === "playstation" && document.getElementById("method").value === "comfortTrade") {
document.getElementById("price").innerHTML = "£2.50";
}
}
</script>
Presuming you have jQuery installed because you are using $(...) in your code, you can solve your issue like this:
<select id="platform" name="platform" onchange="findPrice()">
<option select value=""></option>
<option value="xbox">Xbox</option>
<option value="playstation">PlayStation</option>
<option value="pc">PC</option>
</select><br>
<p>Select Method:</p>
<select id="method" name="method" onchange="findPrice()">
<option selected value=""></option>
<option value="comfortTrade">Comfort Trade</option>
<option value="playerAuction">Player Auction</option>
</select><br>
<h3 id="price"></h3>
<script type="application/javascript">
window.findPrice = function() {
if($("#platform").val() === "xbox" && $("#method").val() === "comfortTrade") {
document.getElementById("price").innerHTML = "£5";
}else if($("#platform").val() === "playstation" && $("#method").val() === "comfortTrade") {
document.getElementById("price").innerHTML = "£2.50";
}
}
</script>
You can see a working example of this at: https://jsfiddle.net/L2vgqmtL/
However, I would actually propose a slightly different solution that I find more elegant:
<script type="application/javascript">
window.findPrice = function() {
var platform = $("#platform").val();
var method = $("#method").val();
var priceUpdateText = "";
if(method == 'comfortTrade'){
switch(platform){
case "xbox":
priceUpdateText = "£5";
break;
case "playstation":
priceUpdateText = "£2.50";
break;
default:
priceUpdateText = "";
}
}
$("#price").text(priceUpdateText);
}
</script>
<select id="platform" name="platform" onchange="findPrice()">
<option select value=""></option>
<option value="xbox">Xbox</option>
<option value="playstation">PlayStation</option>
<option value="pc">PC</option>
</select><br>
<p>Select Method:</p>
<select id="method" name="method" onchange="findPrice()">
<option selected value=""></option>
<option value="comfortTrade">Comfort Trade</option>
<option value="playerAuction">Player Auction</option>
</select><br>
<h3 id="price"></h3>
A working example of this solution is available here: https://jsfiddle.net/8wafskbw/2/
Important Note: Both of these solutions operate under the presumption that have jQuery included in your page.
I have two dropdowns. When I select an option in the first dropdown, the second dropdown values will be changed according to the first dropdown values.
HTML CODE
<select id="one">
<option value="a">A</option>
<option value="b">B</option>
</select>
<select id="two">
<option value="a">A</option>
<option value="b">B</option>
</select>
JS CODE
$("#one").change(function () {
if ($("#one").val() == 'a') {
$("#two").val("b")
} else if ($("#one").val() == 'b') {
$("#two").val("a")
}
});
$("#two").change(function () {
if ($("#two").val() == 'a') {
$("#one").val("b")
} else if ($("#two").val() == 'b') {
$("#one").val("a")
}
});
Both the code for two dropdowns do the same function. Is there any efficient way to reduce the code? Like declaring a common function and using it for both dropdowns (like a prototype)?
Here is the JSFiddle.
Add common class to the both drop-down.
Bind change event on the elements using common class
Use siblings() to set the value of other drop-down
Use trigger() to update the drop-down values on page load.
Demo
$('.mySelect').on('change', function() {
var newVal = $(this).val() == 'a' ? 'b' : 'a';
$(this).siblings('.mySelect').val(newVal);
// Even Shorter
// $(this).siblings('.mySelect').val($(this).val() == 'a' ? 'b' : 'a');
}).trigger('change');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select id="one" class="mySelect">
<option value="a">A</option>
<option value="b">B</option>
</select>
<select id="two" class="mySelect">
<option value="a">A</option>
<option value="b">B</option>
</select>
Like this?
$('#one,#two').on('change', function() {
var other = ( $(this).attr('id') == 'one' ) ? '#two' : '#one';
var value = ( $(this).val() == 'a' ) ? 'b' : 'a';
$(other).val(value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="one">
<option value="a">A</option>
<option value="b">B</option>
</select>
<select id="two">
<option value="a">A</option>
<option value="b">B</option>
</select>
Of course, there are many ways to do it:
function onChange($element, $other) {
if($element.val() == 'a'){
$other.val("b")
}else if($other.val() == 'b'){
$element.val("a")
}
}
See it here:
function onChange($element, $other) {
if ($element.val() == 'a') {
$other.val("b")
} else if ($element.val() == 'b') {
$other.val("a")
}
}
$('#one, #two').change(function() {
var other = $('#one, #two').not(this);
onChange($(this), other);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="one">
<option value="a">A</option>
<option value="b">B</option>
</select>
<select id="two">
<option value="a">A</option>
<option value="b">B</option>
</select>
Make it a function with two arguments to pass your dropdown ids:
$("#one").change(switchSelection("#two", "#one"));
$("#two").change(switchSelection("#one", "#two"));
function switchSelection(x, y) {
if($(y).val() == 'a') {
$(x).val("b")
}
else if ($(x).val() == 'b') {
$(y).val("a");
}
};
The simplest way (given your code) - though not the most efficient - would be to pass the select elements in as parameters to a common function call.
var handleChange = function($select, $linkedSelect){
if($select.val() == 'a'){
$linkedSelect.val("b")
}else if($select.val() == 'b'){
$linkedSelect.val("a")
}
};
$("#one").change(function(){
handleChange($(this),$('#two'));
});
$("#two").change(function(){
handleChange($(this),$('#one'));
});
Here's a fiddle of that in action.
$('#one,#two').change(function() {
var opositeIdObj = {"one":"two","two":"one"};
var opositeValObj = {"a":"b","b":"a"};
$("#"+opositeIdObj[this.id]).val(opositeValObj[this.value]);
}).trigger('change');