How to use the same function in different ways? - javascript

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');

Related

Check if all dropdowns are empty or not jQuery

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;
}

HTML multi select how to deselect all if select first item using jquery

I have a multi select control look like below,
When user select "Any", I want to deselect all other selected values and select only "Any", means, if user select "Any", do not allow to select other values else allow to select other values.
How its possible through jQuery
Thanks...
jQuery("#select").change(function() {
if (jQuery("#select option:first").is(':selected')) {
jQuery("#select").val("any");
}
});
To the form below:
<select multiple id="select">
<option value="any">Any</option>
<option value="...">...</option>
...
</select>
I think you want something like this:
$("select").on("change", function () {
var selOption = $("option:selected", this).val();
if (selOption == "any") {
$(this).attr("selected", false);
$(this).val("any");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="select2" multiple="multiple">
<option value="any">Any</option>
<option value="12">twelve</option>
<option value="13">thirette</option>
<option value="14">fourteen</option>
<option value="15">fifteen</option>
<option value="16">sixteen</option>
<option value="17">seventeen</option>
<option value="18">eighteen</option>
<option value="19">nineteen</option>
<option value="20">twenty</option>
</select>
In most cases this should work
$('.my-select').val('any')
Where is ’any' is a value of Any option.
(function() {
var mSelect;
mSelect = $('select');
mSelect.on('click', function(event) {
var values, needReset;
values = mSelect.val();
needReset = event.target.value === 'any' ||
(values.length > 1 && values.indexOf('any') !== -1);
if (needReset) {
mSelect.val('any');
}
});
}());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select multiple>
<option value="any">Any</option>
<option value="divorced">Maried</option>
<option value="unmarried">Unmarried</option>
</select>

how to disable <select> based on user selection in another <select>

i have two <select>, named category and category_sport
i want <select name='category_sport'> disable , if i click <option>sport</option> in <select name='category'> , i want enable <select name='category_sport'>
Anyone have an idea how ?
function disable()
{
document.getElementById("katOl").disabled=true;
}
function enable()
{
document.getElementById("katOl").disabled=false;
}
the script above is used in <option> ex:
<select name='category'>
<option value="1" onclick='enable()' >sport</option>
</select>
<select id='katOl' name='category_sport'>
<option value="1">Football</option>
</select>
but isn't work
try something like this
javascript
function check(val)
{
if(val == '1'){
document.getElementById("katOl").disabled=true;
}else{
document.getElementById("katOl").disabled=false;
}
}
html
<select name='category' onchange="check(this.value)">
<option value="" >SELECT</option>
<option value="1" >sport</option>
</select>
assuming that your looks like this :
<select name='category_sport' id="katOl"> ... </select>
HTML:
<select id="myselect" name='category' onchange="changeSelect()">
<option value="1">sport</option>
</select>
Javascript:
function changeSelect(){
var mySelect = document.getElementById("myselect");
var selectedValue = e.options[myselect.selectedIndex].value;
if(selectedValue=="1") //sport
{
document.getElementById("katOl").disabled=false;
}
}
try like this
$("#category").change(function(){
if($(this).val()=="yourvalue"){
disable();
}else{
enable();
}
});
You can try this:
$(document).ready(function(){
$('select[name=category]').change(function(){
if($(this).val() === '1'){
$('#katOl').prop('disabled', false);
} else {
$('#katOl').prop('disabled', true);
}
});
});
DEMO Link
use onChange event of select tag instead.
<select onChange="set_sport_cat(this)">
<option value="1">sport</option>
<option value="2">whatever</option>
</select>
function set_sport_cat(my){
alert("test");
if(my.options[0].selected){
alert("1");
}else{
alert("2");
}
}
http://jsfiddle.net/3A6X4/
HTML CODE:
<select name='category' id="category">
<option value="1">sport</option>
<option value="2">education</option>
</select>
<select id='katOl' name='category_sport'>
<option value="1">Football</option>
</select>
js Code:
(function(){
var cat = document.getElementById('category'),
katOl = document.getElementById('katOl');
cat.onchange = function() {
var v = cat.value;
if(v === '1') {
katOl.setAttribute('disabled', 'disabled');
} else {
katOl.removeAttribute('disabled');
}
}
})();
A much simpler and fun approach:
LIVE DEMO
<select name='category'>
<option>Sport</option>
<option>Food</option>
<option>Travel</option>
</select>
<select name='category_sport'>
<option>Football</option>
</select>
<select name='category_food' disabled>
<option>Pizza</option>
</select>
<select name='category_travel' disabled>
<option>Croatia</option>
</select>
jQuery:
$('select[name=category] option').click(function(){
var val = this.value.toLowerCase(); // "Sport" >> "sport"
$('select[name^=category_]').prop('disabled', 1); // Disable all
$('select[name=category_'+ val +']').prop('disabled', 0); // Enable
});
Here is my solution:
HTML:
<select name="category" onchange="alterSelection(event)">
<option value="">----</option>
<option value="1">Sport</option>
<option value="2">Food</option>
</select>
<select id="katOl" name="category_sport" disabled="disabled">
<option value="1">Football</option>
<option value="2">Cricket</option>
</select>
JS:
function alterSelection(e){
if( e.target.selectedIndex==1 ){
document.getElementById("katOl").disabled=false;
}else{
document.getElementById("katOl").disabled=true;
}
}

javascript-dropdown option remove

I have three dropdowns
First dropdown options are
option1
option2
2nd and third dropdowns are
optionA
OptionB
When I select option2 in first dropdown
I should remove optionA from both dropdowns.
When I select option1, my both dropdowns should repopulate with original values.
I am using the following code to remove from one dropdown only
Can anybody point me how to do two dropdowns at same time please.
<script type="text/javascript">
google.load("jquery", "1.4.2");
google.setOnLoadCallback(function()
{
var sites='#firstDDId';
$('#firstDDId').change(function()
{
if($(sites).val()=='Option1' )
{
alert(" Please note, optionA will be removed");
$("#secondDDId option[value='OptionA']").remove();
}
else
{
var exists = false;
$('#SecondDDId option').each(function()
{
if (this.value == 'OptionA')
{
exists = true;
return false;
}
}
);
if (exists==false)
{
$("#SecondDDId").append('<option value="OptionA">OptionA</option>');
}
}
});
});
</script>
Store your options first in an array and then you can repopulate your select options every time you need.
Change $("#secondDDId option[value='OptionA']").remove();
into $("option[value='OptionA']").remove();
This will remove all the options with value OptionA.
if ($("#SecondDDId option[value='OptionA']").length == 0)
$("#SecondDDId").append('OptionA');
This will re-add the option.
To target the second and third drop down at the same time, you could use $("select[id$='DDId'] option[value='OptionA']").
You were on the right track there. You were just missing the dynamic part. I changed some variables and id's for better readability too.
<!doctype html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
</head>
<body>
<select id="control-ddl">
<option value="1">1</option>
<option value="2">2</option>
</select>
<select id="child-ddl-1">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<select id ="child-ddl-2">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<select id ="child-ddl-3">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<select id ="child-ddl-4">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<script>
$(document).ready(function() {
$("#control-ddl").change(function() {
// Array of child select id's; only these get the "A" option
// stripped and readded when control-ddl changes
var ddlIds = [ "#child-ddl-1", "#child-ddl-2", "#child-ddl-3" ];
$.each(ddlIds, function(idx, ddlId) {
if($("#control-ddl").val()=="2") {
$(ddlId + " option[value='A']").remove();
} else {
var exists = false;
$(ddlId + " > option").each(function() {
if (this.value == "A") {
exists = true;
return;
}
});
if (!exists) {
$(ddlId).append("<option value='A'>A</option>");
}
}
});
});
});
</script>
</body>
</html>

Check values of all fields of a certain class

In jQuery, how do I check the values of all option tags inside of a certain div.class to make sure they are set?
var allSet = true;
$(".myClass select").each(function(i, el){
if($(":selected", el).length == 0){
allSet = false;
return false;
}
});
if(allSet == false){
alert("All selects are not set. :(");
} else {
alert("All selects are set. :)");
}
Assuming the value attributes are set to something:
<div class="myClass">
<select>
<option value="">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
$("div.myClass option[value='']").length === 0;
// => false
And if they're not:
<div class="myClass">
<select>
<option>One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</div>
$("div.myClass option[value]").length === 0;
// => false
Of course, those two checks can be combined like so:
0 === $("div.myClass option[value='']").length +
$("div.myClass option[value]").length;

Categories