I am trying to achieve the following thing in my code but it is getting complicated.
I have 'n' dropdowns with or without duplicate values in it.
for simplicity lets assume following scenario:
dropdown1:
<select>
<option>100</option>
<option>200</option>
<option>102</option>
</select>
dropdown 2:
<select>
<option>100</option>
<option>200</option>
<option>201</option>
</select>
dropdown3 :
<select>
<option>100</option>
<option>300</option>
<option>301</option>
</select>
case1:
if user select value 100 from dropdown 1 then 100 should be removed from all the dropdowns.and when user change dropdown 1 value from 100 to 200 then 100 should be added back to all the dropdowns and 200 should be removed from all the dropdowns.
removing seems easy but adding back values is little difficult.
how can I maintain a list or some other data structure to remember which value to add and where incase of multiple value change? is there any advance jquery feature or generic javacript logic i can use ?
If it is sufficient to just disable the option instead of actually removing it, the following could work for you. You might want to adapt the handling of the selects when initially loading the site.
$('select option[value="' + $('select').eq(0).val() + '"]').not(':eq(0)').prop('disabled', true);
$('select').on('change', function() {
var val = $(this).val();
$('select option').prop('disabled', false);
$('select option[value="' + val + '"]').not($(this)).prop('disabled', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value='100'>100</option>
<option value='200'>200</option>
<option value='102'>102</option>
</select>
<select>
<option value='100'>100</option>
<option value='200'>200</option>
<option value='201'>201</option>
</select>
<select>
<option value='100'>100</option>
<option value='300'>300</option>
<option value='301'>301</option>
</select>
It would be better to set display to none instead. Hence, you will avoid the complications of adding or removing in the appropriate order.
So, you can easily return them visible.
$( "option" ).each(function( index ) {
$(this).css("display", "");
});
$("#drop").change(function () {
var selected_value=$(this).val();
var dropdown=$(select);
for(i=0;i<dropdown.length;i++){
$("dropdown[i] option[value=selected_value]").remove();
}
});
Set id of first dropdown="drop"
Here select the value and define it S a variable loop through dropdown with in page remove option when value=selected_value
Related
I would like to do a select option dependent of another select, i saw there's a way using array with fixed values, but my array is reloaded every time we add a new form field on the form. I would like something like when i select op1, then it just show op1 options on second select.
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op2</option>
<option relone="op2">ans 1 op2</option>
</select>
Any idea?
thanks all
Here's a method without jQuery:
When you select an option in the first selectbox, it will hide everything that doesn't match its relone.
var id1 = document.getElementById("id1");
var id2 = document.getElementById("id2");
id1.addEventListener("change", change);
function change() {
for (var i = 0; i < id2.options.length; i++)
id2.options[i].style.display = id2.options[i].getAttribute("relone") == id1.options[id1.selectedIndex].getAttribute("relone") ? "block" : "none";
id2.value = "";
}
change();
<select id="id1" name="optionshere">
<option relone="op1">opt one</option>
<option relone="op2">opt two</option>
</select>
<select id="id2" name="resulthere">
<option relone="op1">ans 1 op1</option>
<option relone="op1">ans 2 op1</option>
<option relone="op2">ans 1 op2</option>
</select>
If Jquery is an option you may go with something like this:
<script type='text/javascript'>
$(function() {
$('#id1').change(function() {
var x = $(this).val();
$('option[relone!=x]').each(function() {
$(this).hide();
});
$('option[relone=x]').each(function() {
$(this).show();
});
});
});
</script>
Then to expand:
There really are many ways in which you can solve this predicament, depending on how variable your pool of answers is going to be.
If you're only interested in using vanilla javascript then let's start with the basics. You're going to want to look into the "onchange" event for your html, so as such:
<select onchange="myFunction()">
Coming right out of the w3schools website, on the Html onchange event attribute:
The onchange attribute fires the moment when the value of the element
is changed.
This will allow you to make a decision based on this element's value. Then inside your js may branch out from here:
You may use Ajax and pass to it that value as a get variable to obtain those options from a separate file.
You may get all options from the second div through a combination of .getElementbyId("id2") and .getElementsByTagName("option") then check for their individual "relone" attribute inside an each loop, and hide those that don't match, and show those that do.
Really, it's all up to what you want to do from there, but I personally would just go for the Jquery approach
What I have:
I have two select elements. <select> #1 is placed before a <table> whereas <select> #2 is placed beneath. The content and function of each element is identical with the exception of the class name.
What I need:
Whenever an option is selected from <select> #1, I need the same option to be selected from <select> #2.
Vice versa.
My code:
Note: The following code does not demonstrate the vice versa.
HTML:
<select class="togglebuildprojecturn_top togglebuildprojecturn">
<option value="allbuildsprojects">All</option>
<option value="prsm-spe-00058">prsm-spe-00058</option>
<option value="buab-tes-00058">buab-tes-00058</option><option value="buab-exs-00058">buab-exs-00058</option>
<option value="nonspecific">Build / Project non-specific</option>
</select>
<!--some table here-->
<select class="togglebuildprojecturn_bottom togglebuildprojecturn">
<option value="allbuildsprojects">All</option>
<option value="prsm-spe-00058">prsm-spe-00058</option><option value="buab-tes-00058">buab-tes-00058</option>
<option value="buab-exs-00058">buab-exs-00058</option> <option value="nonspecific">Build / Project non-specific</option>
</select>
jQuery:
$('.togglebuildprojecturn_top').on('change', function() {
//First attempt that I expected to work...
var selectedbuildprojecturn = $(this).val();
var togglematch = ".togglebuildprojecturn_bottom[value='" + selectedbuildprojecturn +"']"
alert(togglematch); //Just testing here (I know I should be using console logs :-)
$(togglematch).attr('selected', true);
//Testing for targeting without selector as variable...
$(".togglebuildprojecturn_bottom[value='prsm-spe-00058']").attr('selected', true);
});
$('.togglebuildprojecturn_bottom').on('change', function() {
//First attempt that I expected to work...
var selectedbuildprojecturn = $(this).val();
var togglematch = ".togglebuildprojecturn_top[value='" + selectedbuildprojecturn +"']"
alert(togglematch); //Just testing here (I know I should be using console logs :-)
$(togglematch).attr('selected', true);
});
JSFiddle:
For your convenience: http://jsfiddle.net/clarusdignus/rtY75/3/
My question:
Why aren't the necessary options being selected?
You can massively simplify your code by using the class you have on those elements and setting the val() on both to the currently selected value.
$('.togglebuildprojecturn').change(function() {
$('.togglebuildprojecturn').val($(this).val());
});
Example fiddle
So I am writing an app that requires an address input and I have a select element for the user to select the state/province. It needs to support the US and Canada so it has nested optgroups to separate those out and a single, first level option as it's default value. Here is a basic example:
<select name="state" id="state">
<option class="co" value="" data-placeholder="true" disabled selected>Choose your state...</option>
<optgroup label="United States">
<option class="co" value="AL">Alabama</option>
<option class="co" value="AK">Alaska</option>
<option class="co" value="AZ">Arizona</option>
</optgroup>
<optgroup label="Canada">
<option class="co" value="AB">Alberta</option>
<option class="co" value="BC">British Columbia</option>
<option class="co" value="MB">Manitoba</option>
</optgroup>
Now I need to programmatically select the option that matches input from an external source and I want to check for a match based on both the value of the option element or its text. Whichever option is a match would then be set as the selected option. I know you can set the selected option by value using
$("#state").val(myValue)
and I know you can set an option based on text in this way
var myText = "The state I want.";
$("#state").children().filter(function() {
return $(this).text() == myText;
}).prop('selected', true);
Is there a clean way to do this without having to run through each child and checking if it's an optgroup and then running through all its children to check for a match? Is there an easy way through jQuery to combine the value and text methods of setting the selected option?
One other complication, I am going to be doing this within an external jQuery plugin. Within the function I need to modify I have the select element as a variable
$element
so I need a way to do it kind of like this if possible:
$element.descendents(":option").filter(function() {
//do the selecting here
}).prop('selected', true);
If you want to select by the option value, use the value selector:
var myText = "AZ";
$('#state option[value="' + myText + '"]').prop('selected', true);
If you want to search by the option's label, use a filter:
var myText = "Arizona";
$('#state option').filter(function () { return $(this).html() == myText; }).prop('selected', true)
Solved. Since I already had my element passed to a function as a jQuery variable, $element, I couldn't just use the standard selector in the form of:
$("#state option").filter(
// filter function
).prop('selected', true);
After a lot of trying, I got this and it works:
function functionIHadToChange($element, value) {
// other code
$element.find("option").filter(function(){
return ( ($(this).val() == value) || ($(this).text() == value) )
}).prop('selected', true);
}
I am not sure I understood completely your question but I am attempting to answer it in this fiddle
The trick being that you can select it by setting the value of the select box directly
$("#state").val( a_value );
You can set it by $("#select_id").prop("selectedIndex", 3); // Select index starts from zero.
Read here for example this.
$element = $('select#state');
$options = $element.find('option');
$wanted_element = $options.filter(function () {
return $(this).val() == "Alabama" || $(this).text() == "Alabama"
});
$wanted_element.prop('selected', true);
Would be one way to do it.
But i would guess, without knowing the exact internas of the .find() method, in the end jQuery will use at least two loops itself to perform this...
I'm late here but for future visitor, easiest way to do that is :
html
<select name="dept">
<option value="">This doctor belongs to which department?</option>
<option value="1">Orthopaedics</option>
<option value="2">Pathology</option>
<option value="3">ENT</option>
</select>
jQuery
$('select[name="dept"]').val('3');
Output: This will active ENT.
I'm using .val() in jQuery to retain the value of an options menu onChange.
How would I retain the number (as in as it is ordered) of the item in the drop down using jQuery?
<select>
<option> //option 1
<option> //option 2
</select>
Here is what I have set up now:
<select id="start_month" onChange="getMonthDay()">
<option>Jan</option>
<option>Feb</option>
<option>March</option>
<option>April</option>
<select>
Using,
function getMonthDay()
{
$('#start_month').val()
}
I can get whatever value is selected, but my question is how do I get the Number down of this value in the markup? For March, I would want 3.. and so on
Can you reformulate your question better? I'm still lost in what do you want.
But, nevertheless here is how <select> works in jQuery
<select id="selection">
<option value="val_1">value 1</option>
<option value="val_2">value 2</option>
</select>
$("#selection").val() will give you val_1 or val_2 depending on witch item is currently selected.
If you want to go through all options and check the selected on, you can use
$("#selection option:selected").val();
or itenerate through all <option>'s
$("#selection option").each(function() {
if( $(this).is(":selected") ) {
var v = $(this).val();
}
});
If you want to retain all options you can easily clone them or assign them as data, if you want to keep those values throughout the pages, use Local Database or Cookies to persist the data.
To answer your question after your update:
First: Why don't you have:
<select id="start_month" onChange="getMonthDay()">
<option value="1">Jan</option>
<option value="2">Feb</option>
<option value="3">March</option>
<option value="4">April</option>
<select>
And use the value of the selected item?
Second: Just use what I wrote above and itenerate through the options
$("#start_month option").each(function(index, element) {
if( $(this).is(":selected") ) {
// get index position, remember to add 1 as arrays start at 0
var n = index;
// break each
return false;
}
});
You'd get a list of the <option> elements, find the selected one, and use index:
var $opts = $('#start_month option');
var zero_based_index = $opts.index($opts.filter(':selected'));
Demo: http://jsfiddle.net/ambiguous/HyukW/
Just add 1 if you want a one-based index.
I made something like this,with zero based key ;
<select id='deneme'>
<option>Val1</option>
<option>Val2</option>
<option>Val3</option>
<option>Val4</option>
</select>
$('#deneme').change(function(){
$.each( $('#deneme').children('option'),function(key,value){
if($(this).is(':selected'))
alert(key)
})
})
u can check from here http://jsfiddle.net/8JZCw/
No need for any iteration here, let jQuery do that for you, just get the selected index and increment...
$('#start_month option:selected').index() + 1
I have three selects (html drop down lists), all contain the exact same values (except the ids of selects are different).
Now I want to do this:
When a user selects some option in the first select the same option is hidden in the other two. This rule applies to other two selects as well.
If the option in the second select is changed again then the previously selected option must reappear in the other selects.
I hope I was clear. I know this should probably be solved with javascript but I don't have enough knowledge of it to write an elegant solution (mine would probably be very long). Can you help me with the this?
$('#selectboxid').hide();
is the simplest way
http://api.jquery.com/hide/
try toggle it it matches your requirement
http://api.jquery.com/toggle/
you can call these onchange of the select box
if you want to hide individual options
use .addClass and add class to that option to hide it
http://api.jquery.com/addClass/
Little late the party, but here's a full working solution:
HTML:
<select>
<option value="Fred">Fred</option>
<option value="Jim">Jim</option>
<option value="Sally">Sally</option>
</select>
<select>
<option value="Fred">Fred</option>
<option value="Jim">Jim</option>
<option value="Sally">Sally</option>
</select>
<select>
<option value="Fred">Fred</option>
<option value="Jim">Jim</option>
<option value="Sally">Sally</option>
</select>
JavaScript:
$(document).ready(function() {
$("select").change(function() {
var $this = $(this);
var selected = this.options[this.selectedIndex].value;
var index = $this.index();
$("select").each(function() {
var $this2 = $(this);
if($this2.index() != index) {
$(this.options).show();
var $op = $this2.children("option:[value='" + selected + "']");
$op.hide();
if($this2.val() == selected) {
if($op.index() + 1 == $ops.length) {
$this2.val($ops.eq(0).val());
}
else {
$this2.val($ops.eq($op.index() + 1).val());
}
}
}
});
});
});
Also demonstrated here: http://jsfiddle.net/thomas4g/u2sbd/21/