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>
Related
I want select multiple option from second select depending on check option from first select.
For example:
adiunkt -> mikroklimat, RTG
agent celny -> zapylenie
First select:
<select name="form[stanowisko][]" id="stanowisko">
<option value="adiunkt">adiunkt</option>
<option value="agent celny">agent celny</option>
</select>
Second select:
<select multiple="multiple" name="form[czynniki_szkodliwe][]" id="czynniki_szkodliwe">
<option value="mikroklimat">mikroklimat</option>
<option value="RTG">RTG</option>
<option value="zapylenie">zapylenie</option>
</select>
I tried this but it not working (select all options after first check):
function tes(){
if (document.getElementById('stanowisko').value ="agent celny") {
document.getElementById('czynniki_szkodliwe').options[2].selected = true;
document.getElementById('czynniki_szkodliwe').options[0].selected = true;
}
if ( document.getElementById('stanowisko').value="adiunkt") {
document.getElementById('czynniki_szkodliwe').options[1].selected = true;
}
}
Pure js solution.
let elem1 = document.getElementById('stanowisko'),
elem2 = document.getElementById('czynniki_szkodliwe');
elem1.addEventListener('change', (e) => {
Array.from(elem2.children).forEach(v => {
return v.disabled = v.getAttribute('data-attr') !== e.target.value;
})
});
<select name="form[stanowisko][]" id="stanowisko">
<option value="">-</option>
<option value="adiunkt">adiunkt</option>
<option value="agent celny">agent celny</option>
</select>
<select multiple="multiple" name="form[czynniki_szkodliwe][]" id="czynniki_szkodliwe">
<option value="mikroklimat" disabled data-attr='adiunkt'>mikroklimat</option>
<option value="RTG" disabled data-attr='adiunkt'>RTG</option>
<option value="zapylenie" disabled data-attr='agent celny'>zapylenie</option>
</select>
You should use a data attribute to mark the options linked to the first select like this:
$(document).ready(function(){
$("#stanowisko").on("change", function(event){
var $options = $("#czynniki_szkodliwe option");
//Unselect all
$options.prop("selected", false);
var val = $("#stanowisko").val();
$options.each(function(idx, item) {
if($(item).data("stanowisko").indexOf(val) >= 0) {
$(item).prop("selected", true);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="form[stanowisko][]" id="stanowisko">
<option value="">Choose</option>
<option value="adiunkt">adiunkt</option>
<option value="agent celny">agent celny</option>
<option vlaue="lekarz">lekarz</option>
</select>
<select multiple="multiple" name="form[czynniki_szkodliwe][]" id="czynniki_szkodliwe">
<option data-stanowisko='["adiunkt"]' value="mikroklimat">mikroklimat</option>
<option data-stanowisko='["adiunkt","lekarz"]' value="RTG">RTG</option>
<option data-stanowisko='["agent celny"]' value="zapylenie">zapylenie</option>
</select>
Edit: If several options, from the first select, refers to the same options in the second select, you can "store" an array in the data attribute in JSON format.
I updated the JS code to handle JSON array in the data attributes instead of a simple string.
I have two items: a Select List and a Display Image. The Select List has three values for the user to choose from. If the user selects on of the values then the Image View will show a related image with the selected value and if the selected value of the Select List will switch also change the picture.
I tried putting the script in the section: JavaScript -> "Function and Global Variable Declaration" of the page, but not run.
<script language="JavaScript" type="text/javascript">
function setValueDisplayImage(){
if ($("#SELECT_LIST").val() == 1) {
$("#DISPLAY_IMAGE").val('http://www.some.com/img1.jpg');
} else if ($("#SELECT_LIST").val() == 2) {
$("#DISPLAY_IMAGE").val('https://www.some.com/img2.jpg');
} else if ($("#SELECT_LIST").val() == 3){
$("#DISPLAY_IMAGE").val('http://www.some.com/img3.jpg');
}
}</script>
Use jquery on() like,
$(function(){
$("#SELECT_LIST").on('change', function(){
var val=this.value;
if(val==1 || val==2 || val==3){
$("#DISPLAY_IMAGE").val('http://www.some.com/img'+val+'.jpg');
}
});
});
$(function(){
$("#SELECT_LIST").on('change', function(){
var val=this.value;
if(val==1 || val==2 || val==3){
$("#DISPLAY_IMAGE").val('http://www.some.com/img'+val+'.jpg');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="SELECT_LIST">
<option value="1">First Image</option>
<option value="2">Second Image</option>
<option value="3">Third Image</option>
</select>
<br/>
<input id="DISPLAY_IMAGE" style="width:250px;"/>
And if your DISPLAY_IMAGE element is an img then your need to use attr() to change the image src like,
$(function(){
$("#SELECT_LIST").on('change', function(){
var val=this.value;
if(val){
$("#DISPLAY_IMAGE").attr('src','http://placehold.it/250x'+val);
}
}).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="SELECT_LIST">
<option value="">Select</option>
<option value="100">First Image</option>
<option value="150">Second Image</option>
<option value="200">Third Image</option>
</select>
<br/>
<img id="DISPLAY_IMAGE"/>
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');
Edit:I think I have confused you guys with what I need. If I select val1 I need the function to return val1. If I then select val2, with val1 still selected as part of the multi select, I need to return val2. Then I can use the values to set the id and name of rewly created inputs.
I have a select list that has multiple="multiple"
I want to create a text input associated with each selected option and set the id and name of the new input based on the value of each newly selected option, but I always get the value of the first item from the onchange event. Not the first value, but the first selected value. So if I choose val2 first, that is returned, but if I choose val1 first then val2 the id and name will be the same as when val1 is selected.
<select id="multiSelect" multiple="multiple">
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
<option value="val3">Value 3</option>
</select>
I have used the following function and it returns the first value.
$("#multiSelect").on('change', function(evt, params) {
alert($("option:selected", this).val());
});
This will return the first selected option. If I then choose the second option, I still get the first value. I need to get the value of whichever option has been selected.
Thanks in advance.
The workaround is to save previously selected elements and compare them with newly selected ones:
let selectedOptions = [];
$("#multiSelect").on("change", function() {
const newSelectedOptions = $(this).val() || [];
const addedOptions = newSelectedOptions.filter(option => !selectedOptions.includes(option));
const removedOptions = selectedOptions.filter(option => !newSelectedOptions.includes(option));
selectedOptions = newSelectedOptions;
console.log("addedOptions", addedOptions);
console.log("removedOptions", removedOptions);
});
<select id="multiSelect" multiple="multiple">
<option value="value_1">Value 1</option>
<option value="value_2">Value 2</option>
<option value="value_3">Value 3</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You get the selected values on change:
$("#multiSelect").on('change', function () {
var selected = $.map($('option:selected', this),
function (e) {
return $(e).val();
});
alert(selected);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="multiSelect" multiple="multiple">
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
<option value="val3">Value 3</option>
</select>
Try this one : http://jsfiddle.net/csdtesting/jb7ckarp/
$("#multiSelect").on('change', function(evt, params) {
$("#myDiv").append("<span id='mySpan'><input type='text' name='" + $(this).val() + "' value='My name is: " + $(this).val() + "'/>")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="multiSelect" multiple="multiple">
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
<option value="val3">Value 3</option>
</select>
<div id="myDiv">
</div>
Maybe this is what you want, or not :D http://jsfiddle.net/mnm2oaeo/
<select id="multiSelect" multiple="multiple">
<option value="val1">Value 1</option>
<option value="val2">Value 2</option>
<option value="val3">Value 3</option>
</select>
<script type="text/javascript">
var items = [];
$("#multiSelect").on('change', function(evt, params) {
var selected = $(this).val() || [];
if (selected.length == 0)
items.length = 0;
else {
$.each(selected, function(i) {
if (items.indexOf(selected[i]) == -1) {
items.push(selected[i]);
alert(selected[i]);
}
});
}
});
</script>
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>