How to synchronize two SELECT elements - javascript

I was wondering how to synchronize the values and text of two elements. For instance,
<select id="box1" onchange="sync();">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
and then sync(); would look something like....
function sync()
{
box2.selected = box1.selected;
}
Any idea how I would do this?
Thanks,
Matthew

One possible approach:
function sync(el1, el2) {
// if there is no el1 argument we quit here:
if (!el1) {
return false;
}
else {
// caching the value of el1:
var val = el1.value;
// caching a reference to the element with
// with which we should be synchronising values:
var syncWith = document.getElementById(el2);
// caching the <option> elements of that <select>:
var options = syncWith.getElementsByTagName('option');
// iterating over those <option> elements:
for (var i = 0, len = options.length; i < len; i++) {
// if the value of the current <option> is equal
// to the value of the changed <select> element's
// selected value:
if (options[i].value == val) {
// we set the current <option> as
// as selected:
options[i].selected = true;
}
}
}
}
// caching the <select> element whose change event should
// be reacted-to:
var selectToSync = document.getElementById('box1');
// binding the onchange event using an anonymous function:
selectToSync.onchange = function(){
// calling the function:
sync(this,'box2');
};
function sync(el1, el2) {
if (!el1) {
return false;
} else {
var val = el1.value;
var syncWith = document.getElementById(el2);
var options = syncWith.getElementsByTagName('option');
for (var i = 0, len = options.length; i < len; i++) {
if (options[i].value == val) {
options[i].selected = true;
}
}
}
}
var selectToSync = document.getElementById('box1');
selectToSync.onchange = function() {
sync(this, 'box2');
};
<select id="box1">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
JS Fiddle demo.
Or, revised and updated somewhat:
function sync() {
// caching the changed element:
let el = this;
// retrieving the id of the element we should synchronise with
// from the changed-element's data-syncwith custom attribute,
// using document.getElementById() to retrieve that that element.
document.getElementById( el.dataset.syncwith )
// retrieving the <options of that element
// and finding the <option> at the same index
// as changed-element's selectedIndex (the index
// of the selected <option> amongst the options
// collection) and setting that <option> element's
// selected property to true:
.options[ el.selectedIndex ].selected = true;
}
// retrieving the element whose changes should be
// synchronised with another element:
var selectToSync = document.getElementById('box1');
// binding the snyc() function as the change event-handler:
selectToSync.addEventListener('change', sync);
function sync() {
let el = this;
document.getElementById(el.dataset.syncwith).options[el.selectedIndex].selected = true;
}
var selectToSync = document.getElementById('box1');
selectToSync.addEventListener('change', sync);
<select id="box1" data-syncwith="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
JS Fiddle demo.
Note that this approach does assume – and requires – that the <option> elements are in the same order.
To update the original approach, where the order is irrelevant, using ES6 approaches (and the same data-syncwith custom attribute approach):
function sync() {
// caching the changed element (since
// we're using it twice):
let el = this;
// retrieving the id of the element to synchronise 'to' from
// the 'data-syncwith' custom attribute of the changed element,
// and retrieving its <option> elements. Converting that
// Array-like collection into an Array using Array.from():
Array.from(document.getElementById(el.dataset.syncwith).options)
// Iterating over the array of options using
// Array.prototype.forEach(), and using an Arrow function to
// pass the current <otpion> (as 'opt') setting that current
// <option> element's selected property according to Boolean
// returned by assessing whether the current option's value
// is (exactly) equal to the value of the changed element:
.forEach(opt => opt.selected = opt.value === el.value);
}
var selectToSync = document.getElementById('box1');
selectToSync.addEventListener('change', sync);
function sync() {
let el = this;
Array.from(document.getElementById(el.dataset.syncwith).options).forEach(opt => opt.selected = opt.value === el.value);
}
let selectToSync = document.getElementById('box1');
selectToSync.addEventListener('change', sync);
<select id="box1" data-syncwith="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="box2">
<option value="1">One</option>
<option value="3">Three</option>
<option value="2">Two</option>
</select>
JS Fiddle demo.
If you look at the HTML in the Snippet you'll see that I switched the positions of <option> elements in the second <select> element to demonstrate that the <option> position doesn't matter in this latter approach.
References:
Array.from().
Array.prototype.forEach().
Arrow functions.
document.getElementById().
EventTarget.addEventListener().
for loop.
HTMLElement.dataset.
HTMLSelectElement.
let statement.
var.

In the Actual browsers you dont have to do to much...
<select id="box1" onchange="box2.value=this.value;">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="box2">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Jsfiddle DEMO

Without jQuery:
for (var i=0; i<document.getElementById('box1').options.length; i++)
if (document.getElementById('box1').options[i].selected)
for (var j=0; j<document.getElementById('box2').options.length; j++)
if (document.getElementById('box1').options[i].value == document.getElementById('box2').options[j].value)
document.getElementById('box2').options[j].selected = true;

With jQuery:
Note: on method requires jQuery > 1.7
jQuery(function($) {
$('#first').on('change', function() {
var sel = $('option:selected', this).val();
$('#second option').filter(function(index, el) {
return el.value == sel;
}).prop('selected', true);
});
});
<select name="first" id="first" autocomplete="off">
<option value="0">-- Select one option --</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
<option value="5">Fifth</option>
<option value="6">Sixth</option>
</select>
<select name="second" id="second" autocomplete="off">
<option value="0">-- Select one option --</option>
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
<option value="4">Fourth</option>
<option value="5">Fifth</option>
<option value="6">Sixth</option>
</select>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Related

Change option values of select 2 if select 1 has a value with jquery

I require a bit of jQuery to do the following:
A user can currently select Program and/or a region.
If a user selects Program AND a Region I require the option values of the region dropdown to change to "?region=1" and "?region=2"
<select class="program" id="program">
<option value="program1.html">Program 1</option>
<option value="program2.html">Program 2</option>
</select>
<select class="region" id="region">
<option value="region1.html">Region 1</option>
<option value="region2.html">Region2</option>
</select>
Greatly appreciate the assist.
My attempt at JQuery:
$('#program').on('change', function () { if($(this).val() !="0") { } else { // no option is selected } })
You need to further extend the change event for #program and include a similar one for #region.
var programSelected = null;
var regionSelected = null;
$('#program').on('change', function(element) {
programSelected = $('#program option:selected').text();
updateRegionOptions();
});
$('#region').on('change', function(element) {
regionSelected = $('#region option:selected').text();
updateRegionOptions();
});
function updateRegionOptions() {
if(programSelected != null && regionSelected != null) {
$('#region option').each(function() {
var modifiedString = '?';
modifiedString += $(this).val().replace(/\d+/,'');
modifiedString = modifiedString.replace('.html','');
modifiedString += '=';
modifiedString += $(this).val().match(/\d+/);
$(this).val(modifiedString);
});
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="program" id="program">
<option value="" selected disabled>Select Program</option>
<option value="program1.html">Program 1</option>
<option value="program2.html">Program 2</option>
</select>
<select class="region" id="region">
<option value="" selected disabled>Select Region</option>
<option value="region1.html">Region 1</option>
<option value="region2.html">Region2</option>
</select>
Explanation of the logic above:
on('change' event for both #region and #program
Set the relevant variable programSelected or regionSelected depending on the change event
Run function updateRegionOptions();
If the variables programSelected and regionSelected both have a value
For each of the options in #region
Mutate the existing value to be of the form "?region=1" and "?region=2"
Update the value section of each of the option elements to have this value
The relevant JSFiddle for review.
If this solved your issue, please accept this answer :)

Multiple values of <option>

I would like to put multiple values in tag within select, so I could adress precisely one or few items.
Example:
<select id="select1">
<option value="pf, nn">NN</option>
<option value="pf, x2, jj">JJ</option>
<option value="pf, uu">UU</option>
<option value="pf, x2, oo">OO</option>
<option value="tt">TT</option>
<option value="rr">RR</option>
</select>
In my js I got that one function that depend on one value that is common for many items:
if (document.getElementById("select1").value = "pf";) {
// do something;
}
if (document.getElementById("select1").value = "x2";) {
// do some-other-thing;
}
But I don't want to use (cos' and with more options gonna get messy)
var sel1 = document.getElementById("select1").value
if (sel1="nn" || sel1="jj" || sel1="uu" || sel1="oo") {
// do something;
}
if (sel1="jj" || sel1="oo") {
// do some-other-thing;
}
Neverthelesst I need to be able to set item by precise one value
if (document.somethingelse = true) {
document.getElementById("select1").value = "oo";)
}
Is there a nice way to achieve this? Maybe use some other "value-like" attribute of option (but which?)?
Only JS.
I think you can do what you want with selectedOpt.value.split(",").includes("sth") code:
$(document).ready(function(e){
selectedChange($("#select1")[0])
});
function selectedChange(val) {
var selectedOpt = val.options[val.selectedIndex];
var status1 = selectedOpt.value.split(",").includes("x2");
var status2 = selectedOpt.value.split(",").includes("pf");
console.log(status1);
console.log(status2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select1" onchange="selectedChange(this)">
<option value="pf,nn">NN</option>
<option value="pf,x2,jj">JJ</option>
<option value="pf,uu">UU</option>
<option value="pf,x2,oo">OO</option>
<option value="tt">TT</option>
<option value="rr">RR</option>
</select>

Using jQuery to check and see if a select box has/or contains selected options

Using jQuery, upon a change/select event, how can I check and see if multiple select boxes contain any selected items? All I am looking for is how to capture and obtain a total count of this?
Based on a validation if not equal to 0, this would set a buttons default disabled attribute to false.
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br><br>
Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
</form>
$('#myform select).bind("change select",function() {
});
Assuming your <button> is within the form element, the following should work for you:
// binding the anonymous function of the on() method
// as the event-handler for the 'change' event:
$('#myform').on('change', function() {
// caching the $(this) (the <form>, in this case):
var form = $(this);
// finding the <button> element(s) within the <form>
// (note that a more specific selector would be
// preferable), and updating the 'disabled' property,
// finding all <option> elements that are selected,
// filtering that collection:
form.find('button').prop('disabled', form.find('select option:selected').filter(function() {
// retaining only those whose values have a length
// (in order to not-count the default 'empty'
// <option> elements:
return this.value.length;
// and then checking if that collection is
// equal to 0, to obtain a Boolean true
// disabling the <button>, or a false to
// enable the <button>:
}).length === 0);
// triggering the change event on page-load
// to appropriately enable/disable the <button>:
}).change();
$('#myform').on('change', function() {
var form = $(this);
form.find('button').prop('disabled', form.find('select option:selected').filter(function() {
return this.value.length;
}).length === 0);
}).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform">
Cars
<select id="car">
<option value=""></option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br>
<br>Fruits
<select id="fruits">
<option value=""></option>
<option value="apple">apple</option>
<option value="banana">banana</option>
<option value="pear">pear</option>
<option value="strawberry">strawberry</option>
<option value="mango">mango</option>
<option value="orange">orange</option>
</select>
<button>Submission button</button>
</form>
References:
change().
filter().
find().
on().
prop().
You can use the jQuery :checked selector to capture all elements that are checked. For the count, you can do:
$( "input:checked" ).length;
You can then do your condition to view if there are zero or more elements checked:
var selected = $( "input:checked" ).length;
if(selected > 0)
//do something
$('#myform select').on('change', function() {
var count = 0;
$('#myform').find('select').find('option').each(function(){
if ($(this).is(':selected')){
count++;
}
});
if (count < 0){
$('#mybutton').prop('disabled', false);
} else {
$('#mybutton').prop('disabled', true);
});
Grab all the selects on the page and just loop through them while adding a change event to each one.
Then in that change event, call a method that counts up how many selects have items selected.
https://jsfiddle.net/x833qr20/3/
// put an on change event on all the selects, can be done in onload
var ddl = $('select');
for (i = 0; i < ddl.length; i++) {
ddl[i].onchange = function() {
CountAllSelectedDDL();
}
}
// function that fires when one select gets changed
function CountAllSelectedDDL() {
var ddl = $('select');
var count = 0;
for (i = 0; i < ddl.length; i++) {
if (ddl[i].selectedIndex > 0) {
count++;
}
}
var button = document.getElementById('button');
if (count > 0) {
// set the buttons default disabled attribute to false
button.disabled = false;
} else {
button.disabled = true;
}
}
Hope this helps.
Here's a working example via jQuery
https://jsfiddle.net/wedh87bm/
$('#myform select').bind("change select",function() {
var completed = true;
$('#myform select').each(function(){
if($(this).val() == "")
{
completed = false;
}
});
if(completed)
{
$('#validate').prop("disabled",false);
} else
{
$('#validate').prop("disabled",true);
}
});

Remove the duplicate values and combinations in html select option

I have a dynamically generated <select> field with <option>.
<select>
<option value=""></option>
<option value=""></option>
<option value=""> False</option>
<option value=""> True</option>
<option value="">False False</option>
<option value="">False True</option>
<option value="">True</option>
<option value="">True True</option>
</select>
I would like to remove the duplicate occurrences and combinations. The final <select> field with <option> should look like :
<select>
<option value=""></option>
<option value="">False</option>
<option value="">True</option>
</select>
Here is how my fiddle looks like. Been trying to solve this for hours.
var values = [];
$("select").children().each(function() {
if (values.length > 0) {
var notExists = false;
for (var x = 0; x < values.length; x++) {
var _text = this.text.replace(/\s/g, "");
var value = values[x].replace(/\s/g, "");
if (values[x].length > _text.length) {
//console.log('>>+', value, ' || ', _text, value.indexOf(_text))
notExists = value.indexOf(_text) > -1 ? true : false;
} else {
//console.log('>>*', value, ' || ', _text, _text.indexOf(value))
notExists = _text.indexOf(value) > -1 ? true : false;
}
}
if (notExists) {
//this.remove();
values.push(this.text);
}
} else {
values.push(this.text);
}
});
Any help to solve this is appreciated.
You can use map() to return all options text and use split() on white-space. Then to remove duplicates you can use reduce() to return object. Then you can empty select and use Object.keys() to loop each property and append to select.
var opt = $("select option").map(function() {
return $(this).text().split(' ')
}).get();
opt = opt.reduce(function(o, e) {return o[e] = true, o}, {});
$('select').empty();
Object.keys(opt).forEach(function(key) {
$('select').append(' <option value="">'+key+'</option>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value=""></option>
<option value=""></option>
<option value="">False</option>
<option value="">True</option>
<option value="">False False</option>
<option value="">False True</option>
<option value="">True</option>
<option value="">True True</option>
</select>
You can loop through each of this children text , then use substring to get the first text & put it in an array.
Once done empty the select element and append the newly created options
var _textHolder=[]; // NA empty array to hold unique text
var _options="";
$("select").children().each(function(item,value) {
var _textVal = $(this).text().trim(); // Remove white space
//get the first text content
var _getText = _textVal.substr(0, _textVal.indexOf(" "));
// if this text is not present in array then push it
if(_textHolder.indexOf(_getText) ==-1){
_textHolder.push(_getText)
}
});
// Create new options with items from _textHolder
_textHolder.forEach(function(item){
_options+='<option value="">'+item+'</option>'
})
// Empty current select element and append new options
$('select').empty().append(_options);
JSFIDDLE
I would do with pure JS ES6 style. This is producing a words array from the whitespace separated options element's innerText value regardless the words are in the front, middle or the end; and it will create a unique options list from that. Basically we are concatenating these arrays and getting it unified by utilizing the new Set object. The code is as follows;
var opts = document.querySelector("select").children,
list = Array.prototype.reduce.call(opts, function(s,c){
text = c.innerText.trim().split(" ");
return new Set([...s].concat(text)) // adding multiple elements to a set
},new Set());
list = [...list]; // turn set to array
for (var i = opts.length-1; i >= 0; i--){ //reverse iteration not to effect indices when an element is deleted
i in list ? opts[i].innerText = list[i]
: opts[i].parentNode.removeChild(opts[i]);
}
<select>
<option value=""></option>
<option value=""></option>
<option value=""> False</option>
<option value=""> True</option>
<option value="">False False</option>
<option value="">False True</option>
<option value="">True</option>
<option value="">True True</option>
</select>

How to get the display value of Select using javascript

<Select>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</Select>
I am using document.getElementById("Example").value; to get the value.
I want to display the text instead of the value. eg. value=1 --> One. How can I get the One text?
In plain JavaScript you can do this:
const show = () => {
const sel = document.getElementById("Example"); // or this if only called onchange
let value = sel.options[sel.selectedIndex].value; // or just sel.value
let text = sel.options[sel.selectedIndex].text;
console.log(value, text);
}
window.addEventListener("load", () => { // on load
document.getElementById("Example").addEventListener("change",show); // show on change
show(); // show onload
});
<select id="Example">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
jQuery:
$(function() { // on load
var $sel = $("#Example");
$sel.on("change",function() {
var value = $(this).val();
var text = $("option:selected", this).text();
console.log(value,text)
}).trigger("change"); // initial call
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="Example">
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Here the selected text and value is getting using jquery when page load
$(document).ready(function () {
var ddlText = $("#ddlChar option:selected").text();
var ddlValue = $("#ddlChar option:selected").val();
});
refer this
http://csharpektroncmssql.blogspot.in/2012/03/jquery-how-to-select-dropdown-selected.html
http://praveenbattula.blogspot.in/2009/08/jquery-how-to-set-value-in-drop-down-as.html
This works well
jQuery('#Example').change(function(){
var value = jQuery('#Example').val(); //it gets you the value of selected option
console.log(value); // you can see your sected values in console, Eg 1,2,3
});

Categories