How to copy selection from one select to another? - javascript

I have two select elements, with same number of options, and same values for these options, but different (translated) texts.
How can I copy selection from one to another?
From user perspective, if someone will select "red" (value=1) and "brown" (value=5) in English select, I want "rubrum" (value=1) and "rufum" (value=5) to appear selected in Latin select.
For <input> tags, this works:
$(this).closest('.common-parent')
.find(".common-identifier")
.not(this)
.val( $(this).val() );
Sadly, this omits <select> tags.
I found many ways to copy items, but can't find a way to copy actual selection.
Fiddle here: http://jsfiddle.net/e53aJ/8/
Edit: I'd love it to work both for single and multiselect, if possible. I know at first I did not reflect that in my fiddle, sorry.

I saw your html markup there you supplied all option values to 1 that should be in order like below:
Html:
<div class=".common-identifier">
<select name="english" class=".common-identifier">
<option value=1>red</option>
<option value=2>green</option>
<option value=3>yellow</option>
<option value=4>blue</option>
<option value=5>brown</option>
</select>
<select name="latin" class=".common-identifier">
<option value=1>rubeum</option>
<option value=2>viride</option>
<option value=3>flavus</option>
<option value=4>caeruleo</option>
<option value=5>brunneis</option>
</select>
</div>
jQuery:
$('select[name="english"]').on('change', function () {
$('select[name="latin"]').val(this.value);
});
Fiddle

<select> elements have a property selectedIndex that indicates which of their options is selected.
If you get the selectedIndex of the one <select>, then set the selectedIndex of the other <select> to that, you should get the result you're looking for.
However, if your <select> accepts multiple selections (as your question implies), then it's a bit more tiresome. You have to loop through the <option> elements and check each one to see whether it's selected property is true.
(This is why jQuery's popular: the JavaScript DOM interface frequently sucks.)

$(this).closest('.common-parent')
.find(".common-identifier")
.not(this)
.attr('selectedIndex', $(this).attr('selectedIndex'));

Related

Replace text for every first child for multiple items

Two identical select boxes
<select class="select">
<option>- OPTION -</option>
<option>1</option>
<option>1</option>
</select>
<select class="select">
<option>- OPTION -</option>
<option>1</option>
<option>1</option>
</select>
Replace - OPTION - with - SELECT -
$(".select option:first").text("- SELECT -");
Code above replaces only first select box, ignores the second. Why? How to apply to all/any?
https://jsfiddle.net/oLbfs901/2/
:first will only select the first element of all the options combined together.
:first-child will select all elements that are the first child of their parent.
$(".select option:first-child").text("- SELECT -");
UPDATE regarding speed
Below, user #kosmos suggested using .find(). This method is much less performant than using :first-child. Some developers usually don't think twice about performance because it's still really quick but these can add up. Now you know that faster ways exist to achieve the same result so I would suggest using this knowledge.
This is the test case I set up to confirm: http://jsperf.com/find-versus-first-child
Though the other answers are valid, you could also type
$(".select").find("option:first").text("- SELECT -");
to get all .select elements and, for each one, get the first option child.
you can try with below code
$(".select option:first-child").text("- SELECT -");

JS keep to selects in sync (no jquery)

I have two SELECT elements on a page and what I need to do is if the first one is changed, have the second contain all the OPTIONS from the first except the one that is currently selected in the first.
They start off with identical options and I can disable the second until the first is selected if needed. So, if I have:
...
<select id="selectOne" onchange="someFuntion()">
<option value="1">One</>
<option value="2">Two</>
<option value="3">Three</>
</select>
<select id="selectOne" onchange="someFuntion()">
<option value="1">One</>
<option value="2">Two</>
<option value="3">Three</>
</select>
...
...and Two is selected in the first, then it should be removed from the second. Then if Three is selected in the first, the second should have everything in listed in the first (including Two again) except Three. The first ones options never change and the second should always have everything in the first except the currently selected option. Any ideas on how best to accomplish something like this?
I cannot bring JQuery into the mix for this, so please no Jquery specific answers. Beyond that open to pretty much anything. I can get the initial value selected in the first removed from the second, but am not sure how to handle changes from there.
TIA!
If disabling the options in selectTwo is fine, you might do something like this. If not, you might "hide" the matching option with a display:none class and use classList.add and classList.remove to hide and show rather than disable and enable.
Both the hide and disable methods here result in the possibility that the item to remove is the once currently selected in selectTwo. Neither strategy is great in that situation. If you must avoid it, you might either set the value of selectTwo to a "good" one or alternatively, delete the children of selectTwo and clone the non-selected children of selectOne and add those to selectTwo.
If you want an example of the remove/clone strategy let me know and I will post that.
function selectClick(event) {
var that = document.querySelector("#selectTwo");
var thatOptions = that.querySelectorAll("option");
for (var i = 0; i < thatOptions.length; i++) {
thatOptions[i].disabled = (thatOptions[i].value === this.value);
}
}
document.querySelector("#selectOne").addEventListener("change", selectClick);
<select id="selectOne">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="selectTwo">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>

JQuery - Remove all option from Selectbox except for first and selected

I have a html select box with several options. Upon selection of an option I want Only the selected option and the first option to be shown in the select option dropdown. I know how to filter and show only one option but I cannot figure out how to include both option where the 'selected' option remains 'selected'. I have include snippets similar to of my code as well as a demo.HTML:
<select id="myDropdown">
<option selected>Select fruit</option>
<option>Grapes</option>
<option>Bananas</option>
<option>Oranges</option>
<option>Apples</option>
</select>
JS:
$(document).on('change', '#myDropdown', function() {
$('option', this).not(this,'option:gt(0)').siblings().remove(); });
I am trying to use the first option to perform another function 'on change' so I need the selected option to remain selected while the rest being filtered out except for the first. For example if 'Oranges' were selected, this is what you would see:
<select id="myDropdown">
<option>Select fruit</option>
<option>Oranges</option> //selcted value
</select>
BTW I am using jquery mobile to style as well.
jsfiddle
.not only takes 1 parameter. If you want to filter on two different selectors, you can add a comma between them inside the string. You can also use the :selected selector:
$('option', this).not(':eq(0), :selected').remove();
See Updated Fiddle: http://jsfiddle.net/znx9hxvu/9/

How to refresh default display option in select by javascript or jquery?

html code:
<select>
<br>
<option>1</option><br>
<option>2</option><br>
</select>
This select will default display the first option item(display 1).
Now i want to change select to display the second item by jquery when dom is ready, but i tried several times, all failed.The following is my attempt:
$('select').prop('selectIndex', 1);
$('option').eq(1).attr('selected', 'selected');
$('option').eq(1).prop('selected', true);
default set select's style to 'display:none' in html code, then try above three ways and finally invoke $('select').show()
Maybe, i am only setting the dom value, not tell browser to refresh 'select'.
Do you konw the other way to refresh default display option in select?
You have to add values to your options from select.
<select>
<option value="1">First</option>
<option value="2">Second</option>
</select>
Then, just set the value "2".
$("select").val("2");
Or, you can do this simply setting the second value from select.
$("select").val(2);
See the working example here.
This is enough
$("select").val(2);
i think you want to select option 2 when page is load.
<select>
<option>1</option>
<option selected="selected">2</option>
</select>

knockout using one option list for selectedOptions on multiple selectboxes

http://jsfiddle.net/E2AMX/ has the exact demonstration of the problem, which is:
I have multiple select boxes on the same page. All the options of the selectboxes are in the given form:
<option value="#id_num">StringVal</option>
and i have one observableArray (say idlist) of id_nums with no separation regarding selectboxes. For example,
idlist = ko.observableArray([1,2,3,4]);
and the selectboxes are as
<select name="first" data-bind="selectedOptions: idlist">
...
<option value="2">Blah</option>
<option value="3">Blah</option>
...
</select>
<select name="second" data-bind="selectedOptions: idlist">
...
<option value="1">Blah</option>
...
</select>
<select name="third" data-bind="selectedOptions: idlist">
...
<option value="4">Blah</option>
...
</select>
My problem is: when i select one option from a selectbox, other selectboxes return to their initial states. This is directly related to selectedOptions, for if i remove the selectedOptions directive, this problem does not occur.
Any suggestions will be very welcomed.
Thanks.
The selectedOptions binding is meant to be used on a single <select> tag with multi-select enabled. It will keep an array of each item in the options box selected.
The reason you are seeing the behavior you are is because when you you select a single value from one of the drop downs, the selectedOptions binding immediately fires. The logic goes something like this:
Update on target <select> fires.
Binding extracts the value from <option> and updates the underlying observable array.
Observable array fires update since values have changed.
Secondary drop downs respond to update, and update their selected value based on what is in the array.
Since no value exists in the set of <option> tags, the value is cleared.
This is why you are seeing this behavior. If you want to collect a composite from all selected options, then you will either need to write a new custom binding, or create a seperate array for each <select> you want to bind to.

Categories