Get pre-selected value of an HTML select element - javascript

Or through example, how can one retrieve "c" via JavaScript or jQuery no matter if the user changed it?
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
I tried the following, however, it returns the value of the currently selected menu. I suppose I can take a similar approach which runs upon page load and save the value, but expect there is a more "proper" way to do so.
$('#select-menu > option').each(function(i){
if(this.selected) {
console.log(this.value)
$("#submit").val(this.value);
return false;
}
})

Use jQuery .attr() to get initial value:
function get_initial(){
$('#select-menu > option').each(function(i){
if($(this).attr('selected')) {
console.log('initial: ' + this.value)
}
if(this.selected) {
console.log('current: ' + this.value)
}
})
}
$('.initial').on('click', get_initial);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>
<button class="initial">check initial</button>

There is no better way. A select is meant to be user-modifiable.
If you want to retain the original value you could save it on load:
$(document).ready(function() {
var initialValue = $("#select-menu").val();
});
You could also write it in a hidden input:
<input type="hidden" name="initial-select-menu" value="c">
This way has the benefit that the value will be submitted along with the rest of the form. Might be preferable in some cases.
Or you could stuff that initial value in a data attribute:
<select id="select-menu" data-initial="c">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>

You could save the value on an html5 data-* attribute:
<select id="select-menu" data-default="c">
And get it with
$("#select-menu").attr("data-default");

The following code exhibits various examples related to getting of values from select fields using JavaScript.
Working Snippet
const selectMenu = document.getElementById("select-menu");
var selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
/*Option 1*/
selectMenu.onchange = function() {
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
}
/*Option 2*/
/*selectMenu.addEventListener("change", function(){
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
})*/
/*Option 3*/
/*function updateSelectedIndex() {
selectedIndex = selectMenu.options[selectMenu.selectedIndex].value;
}*/
document.writeln(selectedIndex);
<!-- Option 3 -->
<!-- <select id="select-menu" onchange="updateSelectedIndex"> -->
<select id="select-menu">
<option value="a">A</option>
<option value="b">B</option>
<option value="c" selected>C</option>
<option value="d">D</option>
</select>

Try this for the appropriate cases:
let preselectedOption = $(targetDropDown).find('option[selected]');
let currentOption = $(targetDropDown).find('option:selected');

Related

How to force a select to keep always the same selected value

Let's say we have multiple forms, each form has 40 selects, the ids of each select have the following structure:
#id_form-X-{field_name}
Let's say for example, of those 40 selects, we want 3 of them to be unmodifiable for each form when we change the value of the select, so it will always show the same selected value.
The 3 selects we want to change have the following field_name: ps2_0, ps2_1 and ps2_3.
So I'm looking for a generic solution that works for:
id_form-0-ps2_0
id_form-0-ps2_1
id_form-0-ps2_3
id_form-1-ps2_0
id_form-1-ps2_1
id_form-1-ps2_3
id_form-N-ps2_0
id_form-N-ps2_1
id_form-N-ps2_3
...
...
...
Dummy example:
<select name="cars" id="cars">
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
If, for example, the user clicks on the select and selects, for example Saab, the select will show again the value selected by default: Volvo.
I cannot use the 'readonly' or 'disabled' properties for the selects.
What I've tried so far:
$(document).ready(function() {
var previous = "initial prev value";
$("select").on('click', function () {
previous = $(this).val();
}).change(function() {
$(this).val() = previous;
});
});
I'm trying to 'force' the changed select to keep the previous value but didn't work.
Simple Solution
Reset the value of select with initial value on change.
const selectDD = document.getElementById('cars');
const selectedNode = selectDD.value;
selectDD.onchange = (e) => {
selectDD.value = selectedNode;
}
<select name="cars" id="cars">
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
Much Generic Solution
There should be some unique identifier to differentiate between nodes that can be changed and those to be kept unchanged. Here I have added an unchanged custom attribute to select. Pick thode nodes with that custom attribute and on change of that select, reset its value to initial value.
Example
const selectDD = document.querySelectorAll('[unchanged]');
selectDD.forEach((node) => {
node.attributes.initialValue = node.value;
node.onchange = (e) => {
e.target.value = node.attributes.initialValue;
}
})
You cant change this
<select name="cars" id="cars" unchanged>
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br/>
You cant change this
<select name="gender" id="gender" unchanged>
<option selected value="male">Male</option>
<option value="female">female</option>
</select>
<br/>
You can change this
<select name="age" id="age">
<option selected value="10">10</option>
<option value="15">15</option>
</select>
If you use querySelectorAll to generate a nodelist of all the select menus you could assign a default attribute( using dataset here for instance) and set the value within an event listener so that this default attribute is always selected
document.querySelectorAll('form select').forEach( sel => {
sel.dataset.def=sel.options[sel.selectedIndex].value;
sel.addEventListener('change',function(e){
this.value=this.dataset.def
})
})
<form>
<select name='cars'>
<option selected value='volvo'>Volvo
<option value='saab'>Saab
<option value='mercedes'>Mercedes
<option value='audi'>Audi
</select>
<select name='fruit'>
<option selected value='apple'>Apple
<option value='banana'>Banana
<option value='mango'>Mango
<option value='plum'>Plum
</select>
</form>
Maintain an object which specifies the restricted Select items and the indexes they should always defaults to
let allowedIndexes = {
cars: 0,
bikes: 1
}
function preventChange(e) {
if (Object.keys(allowedIndexes).includes(e.currentTarget.id)) {
let fixedIndex = allowedIndexes[e.currentTarget.id];
e.currentTarget.selectedIndex = fixedIndex;
}
}
<select name="cars" id="cars" onChange="preventChange(event)">
<option selected value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<select name="bikes" id="bikes" onChange="preventChange(event)">
<option value="honda">honda</option>
<option selected value="kavasaki">kavasaki</option>
<option value="suzuki">suzuki</option>
<option value="yamaha">yamaha</option>
</select>
It's somewhat uncomfortable when one's answer is copied.

Bind event on select option

I have the following HTML
<select>
<option value="">filter</option>
<option data-behavior="toggle-visibility" data-scope="a" value="a">a</option>
<option data-behavior="toggle-visibility" data-scope="b" value="b">b</option>
</select>
and I need to fire up a Javascript callback when any of the options is selected.
I have the following piece of Javascript:
$(function() {
$(document).on("EVENT", "[data-behavior~=toggle-visibility]", function() {
...
});
});
Is there an event I can use to achieve my goal?
PS - I understand I could move data-behavior="toggle-visibility" to the select tag and then listen for change and get the currently selected value. However, since that piece of Javascript is already used with other elements, I need to keep the data-behavior attribute on the options.
It should work here https://jsfiddle.net/xpvt214o/535895/
You should be using on change event instead:
The example is as follows:
$("select").on("change", function(e) {
var sel = $(this).find(":selected");
var attr = sel.attr("data-behavior");
console.log(attr + "....." + $(this).val())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="">filter</option>
<option data-behavior="toggle-visibility" data-scope="a" value="a">a</option>
<option data-behavior="toggle-visibility" data-scope="b" value="b">b</option>
</select>
Html Code:
<select id="maker-list">
<option value="">filter</option>
<option data-behavior="toggle-visibility" data-scope="a" value="a">a</option>
<option data-behavior="toggle-visibility" data-scope="b" value="b">b</option>
</select>
JavaScript code:
$('#maker-list').off('change').on('change', e => {
selectedValue = $('#maker-list').val();
// Here you can call another function with selectedValue
});
In above JavaScript Code, we bind change even and unbind the same event after selecting value so that it will not fire twice. jquery help
I hope this will work ... happy coding :)
$("select").on("change", (e) => {
console.log(e.target.value)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="">filter</option>
<option data-behavior="toggle-visibility" data-scope="a" value="a">a</option>
<option data-behavior="toggle-visibility" data-scope="b" value="b">b</option>
</select>

javascript - Hide Options from Multiple Selection Box when an option from another select is selected

I need your help. So what I want to do is when a user select an option from one select, automatically hide an option from another multiple select.
Example:
if a user choose Car from select A, I want the car option from the select B to be automatically removed or hidden.
select A:
<select name="my_option_one" required id="id_my_option_one">
<option value="" selected>Choose..</option>
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
Select B:
<select name="my_option_two" id="id_my_option_two" multiple="multiple">
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
This is what I have tried but none of it worked.
$(document).ready(function() {
$("#id_my_option_one").change(function() {
if ($(this).val() === 'C') {
$("#id_my_option_two option[value='C']").options[0].remove();
$('select[name=my_option_two] option:eq(1)').hide();
$("#id_my_option_two option[value=" + 'C' + "]").hide();
$("#id_my_option_two option[value='C']").attr('disabled','disabled').hide();
}
});
});
function my_optionsChange() {
$("#id_my_options_two option").show(); //.css("display", "block");
$("#id_my_options_two option[value='" + $("#id_my_options").val() + "']").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<select name="my_options" required id="id_my_options" onchange="my_optionsChange()">
<option value="" selected>Choose..</option>
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
<select name="my_options_two" id="id_my_options_two" multiple="multiple">
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
I made an example which is longer because it's split into parts so you understand better what is going on.
I tried to name the variables so that it's clear what they are, but if you have any questions, please ask in the comments.
Let me know if this works for you.
const firstSelect = $('#id_my_options')
const secondSelect = $('#id_my_options_two')
firstSelect.on('change',function() {
const selected = $(this).find('option:selected');
const selectedValue = selected.val()
const secondOptions = secondSelect.children();
secondOptions.each(function() {
const secondValue = $(this).val()
secondValue === selectedValue ? $(this).hide() : $(this).show()
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="my_options" required id="id_my_options">
<option value="Choose" selected>Choose..</option>
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
<select name="my_options_two" id="id_my_options_two" multiple="multiple">
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
<select name="my_options" id="firstblock" onchange="disable(2,this.value);">
<option value="" selected>Choose..</option>
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
<select name="my_options" id="secondblock" onchange="disable(1,this.value);">
<option value="" selected>Choose..</option>
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
<script>
function disable(needtoblock,val){
console.log(needtoblock+" "+val);
if(val != ""){
if(needtoblock == 1){
$("#firstblock option[value='"+val+"']").prop('disabled', true);
}else if(needtoblock == 2){
$("#secondblock option[value='"+val+"']").prop('disabled', true);
}else{
}
}else{
$("#secondblock option").prop('disabled', false);
$("#firstblock option").prop('disabled', false);
}
}
</script>
This is how code could look, definetly you need to update and make it suitable for you.
I know, this is a bit late, but maybe it is of interest to someone out there. I understood the demand of OP so, that the hiding of options was to be done in any direction, or potentially spanning over multiple selector boxes. The following script will do exactly that: if you select an option in one selector it will go through the other selectors of the defined group $grp (by doing $grp.not(this).each((i,trg)=> ...)) and will hide/show all options there, depending of whether thay have been selected elsewhere already.
The $(to).toggle(...) method sets the visibility of each option (to) within trg, based on the existence of selected options with the same value in the sibling selectors of trg (again, limited to the current group $grp).
Maybe the script is a little too condensed for easy reading but it shows how much you can achieve with very little code when you use the power of jQuery.
const $grp=$('select[id^=id_my_options]') // define the selector group
$grp.on('change',function(ev){ // bind the change event ...
$grp.not(this).each((i,trg)=> // work on each sibling-selector (trg) of clicked
// selector (this), but only within jquery
// selection $grp
$('option[value!=""]',trg).each((j,to)=> // for all options of sibling-selectors of
// trg (within jquery selection $grp):
$(to).toggle($grp.not(trg).find('option[value='+to.value+']:selected').length==0))
// toggle the visibiltiy of that option
)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="my_options" required id="id_my_options">
<option value="" selected>Choose..</option>
<option value="C">Car</option>
<option value="H">House</option>
<option value="A">Airplane</option>
</select>
<select name="my_options_two" id="id_my_options_two" multiple="multiple">
<option value="C">Car2</option>
<option value="H">House2</option>
<option value="A">Airplane2</option>
</select>
<select name="my_options_three" id="id_my_options_three" multiple="multiple">
<option value="O">yet another option</option>
<option value="C">Car3</option>
<option value="H">House3</option>
<option value="A">Airplane3</option>
</select>
<br><br>
<select name="my_options_four" id="id_your_options_four" multiple="multiple">
<option value="O">and some unrelated options</option>
<option value="C">Car3</option>
<option value="H">House3</option>
<option value="A">Airplane3</option>
</select>

How to set selected option for select with same name?

I am getting an array of objects with education data with AJAX and PHP. There can be up to 4 different <select></select> tags to display. How can I set the correct option for each select and remove the duplicate?
I tried this, which causes the duplicate:
<div class="col-md-3">
<label>Levels</label>
<div class="form-group form-group-custom">
<select type="text" class="form-control" placeholder="Degree..." id="userEducationDegree educationCount + '" name="userEducationDegree[]">
<option value="' +data.degree_name + '">' + data.degree_name + '</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
Then I tried removing the duplicate with JS, which only works with the first select tag:
var usedDegrees = {};
$("select[name='userEducationDegree[]'] > option").each(function () {
console.log("removing");
if(usedDegrees[this.text]) {
$(this).remove();
} else {
usedDegrees[this.text] = this.value;
}
});
Current output what I have with the above setup is:
<option value="A">A</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
What I would like is that the one of <option value="A">A</option> is removed or that <option> is selected.
You don't need to select the corrected value like you did. The duplicate option comes from your selection which is not required.
Just use the below line it will automatically select the value with match string.
Jquery
$("select[id^='userEducationDegree']").val('A');
// in your case it should be data.degree_name instead of 'A'
Here is the Snippet
$(function(){
$("select[id^='userEducationDegree']").val('A');
$("#sel").html('`'+$("select[id^='userEducationDegree']").val()+'`');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select type="text" class="form-control" placeholder="Degree..." id="userEducationDegree educationCount + '" name="userEducationDegree[]">
<option value="-1">--Select--</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
<p>See <strong id="sel"></strong> is selected</p>
As per your requirement
I would like is that the one of A is
removed or that is selected.
we can select the option as per degree name. for this you can try this code
html:
<div class="col-md-3">
<label>Levels</label>
<div class="form-group form-group-custom">
<select type="text" class="form-control" placeholder="Degree..." id="userEducationDegree educationCount + '" name="userEducationDegree[]">
<option value="Select">Select</option>
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
</div>
</div>
js code will go like that
//lets degree_name='B';
var degree_name='B';
$("select[name='userEducationDegree[]'] option").each(function () {
if(degree_name===this.value) {
this.selected=true;
}
});
Hope it will work fine for you.

Two HTML selects with differing selected values

I got following HTML code:
<select id="first">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
So both of them have same data. I need to secure, that user can't select same value in both of them.
I hoped, that JQuery has some nice feature like:
$("#first").getOptions()
or even
$("#first").setOptions()
but unfortunately, it doesn't. This makes it very complicated for me, because I don't know JQuery very well ...
So, what is the best approach to solve my problem?
You can get the value of the currently selected option by doing:
$('#first option:selected').text();
$('#second option:selected').text();
Assuming I understand your question, you don't want the user to be able to enter the same value in each box. So, something similar to:
$first = $('#first');
$second = $('#second');
$first.on('change', function() {
$second.find('option').attr('disabled', false);
var firstVal = $first.find('option:selected').text();
$second.find('option:contains("'+ firstVal +'")').attr('disabled', true);
});
$second.on('change', function() {
$first.find('option').attr('disabled', false);
var secondVal = $second.find('option:selected').text();
$first.find('option:contains("'+ secondVal +'")').attr('disabled', true);
});
I should probably note that there are ways for you to achieve your getOptions() and setOptions() ideas, you can do $select.find('option') to get the options. For setting them, define some options in html and set the select element's innerHTML to those elements:
var options = '<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>';
$select.html(options);
JSFiddle demo
You can disable single options in your select
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2" disabled>Two</option>
<option value="3">Three</option>
</select>
Handle event onSelect on first select and based on it disable proper <option> in second select
When one is changed, if the other is the same, you could change it back to default, like this.
$(document).on('change', '#first', function() {
var firstVal = $('#first').val();
var secondVal = $('#second').val();
if (firstVal == secondVal) {
$('#second').val(0);
}
});
$(document).on('change', '#second', function() {
var firstVal = $('#first').val();
var secondVal = $('#second').val();
if (firstVal == secondVal) {
$('#first').val(0);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="first">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Try this(codepen):
HTML:
<select id="first">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
<select id="second">
<option value="0" selected="selected"> default </option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
Javascript/jQuery:
var strUser;
var strUser2;
$(function() {
$("#first").change(function() {
var e = document.getElementById("first");
strUser = e.options[e.selectedIndex].text;
if (strUser == strUser2) {
alert("Dropdowns contain the same value. Change one.")
document.getElementById("first").disabled=true;
} else {
document.getElementById("second").disabled=false;
}
});
});
$(function() {
$("#second").change(function() {
var e = document.getElementById("second");
strUser2 = e.options[e.selectedIndex].text;
if (strUser2 == strUser) {
alert("Dropdowns contain the same value. Change one.")
document.getElementById("second").disabled=true;
} else {
document.getElementById("first").disabled=false;
}
});
});
Essentially, this code will retrieve selected values from the dropdowns on change, and then a comparison will be made. If the values are equal, the recently selected dropdown will be disabled. You then will have to select a different value in the other dropdown to re-enable the disabled dropdown. Here's the codepen that displays the working functionality. This will not allow a user to select two of the same values without a dropdown being disable and turned off.

Categories

Resources