I have a select2 that uses the sorter option to sort options alphabetically, and a button that should select the next option after the currently selected option. All of this works as desired except the button does not select the next (alphabetical) choice in the select2, which is what I would like; instead it selects the next <option> element in the underlying <select> that drives the select2. These <option>'s are not sorted alphabetically. Obviously I could manipulate the DOM to sort them alphabetically, but that sort of defeats the purpose of leveraging the sorter option. Is there any way to identify the option that comes after the currently selected one, in the sorted list?
HTML
<select id="employeeSelect">
<option value="abc">Diane Smith</option>
<option value="xyz">Tim Carter</option>
<option value="dmv">Keith Appleton</option>
<option value="r2d2">Carla Peters</option>
</select>
<button id="nextEmployee">Next</button>
JS
$('#employeeSelect').select2({
placeholder: '-- select an employee --',
sorter: data => data.sort((a, b) => a.text.localeCompare(b.text)),
})
$('#nextEmployee').on('click', function(){
$("#employeeSelect > option:selected")
.prop("selected", false)
.next()
.prop("selected", true);
$('#employeeSelect').trigger('change');
})
I didn't find any documentation on this, but from inspecting the select2 element's data properties, it appears that the sorted list is not held in the select2's internal data in any way (I think it is generated on the fly when the dropdown is clicked); therefore, this is probably not possible other than by sorting the <option> tags.
So my current solution looks like this:
$('#nextEmployee').on('click', function(){
const isBefore = function (a, b)
{
return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase()) < 0
}
const selectedOption = $("#employeeSelect > option:selected")
const nextOption = $('#employeeSelect').find('option').toArray()
.reduce(function (acc, thisOption)
{
if (isBefore(selectedOption, thisOption)
&& (!acc || isBefore(thisOption, acc)))
{
return thisOption
} else
{
return acc
}
}, null)
if (nextOption)
{
selectedOption.prop("selected", false)
$(nextOption).prop("selected", true);
$('#employeeSelect').trigger('change');
}
}
to automate CRUD functionality I need to select the 2nd item from a static drop down and the html is like
<select name="segment[segment_contact_id]" id="segment_segment_contact_id">
<option value="73082">Rita Basu</option>
<option value="73349">researcher user</option>
</select>
So by using cypress I am using the hardcoded value and my code is like
const segmentUser2 = 'researcher user'
const userValue2 = 73349
cy.get('select#segment_segment_contact_id')
.select(segmentUser2)
.should('have.value', userValue2)
I need suggestion because I don't like to use the hardcoded value instead I would like to use always the 2nd item from the drop down dynamically.
You could do something like this
Cypress.Commands.add(
'selectNth',
{ prevSubject: 'element' },
(subject, pos) => {
cy.wrap(subject)
.children('option')
.eq(pos)
.then(e => {
cy.wrap(subject).select(e.val())
})
}
)
Usage
cy.get('[name=assignedTo]').selectNth(2)
Here is #ItsNotAndy's way without the custom command.
cy.get('select#segment_segment_contact_id')
.children('option').eq(1)
.then($option => {
cy.wrap($option).parent().select($option.val())
})
As a function
function selectNth(selector, pos) {
cy.get(selector)
.children('option').eq(pos)
.then($option => {
cy.wrap($option).parent().select($option.val())
})
}
selectNth('select#segment_segment_contact_id', 1)
Verifying from text displayed
cy.get('select#segment_segment_contact_id')
.find(':selected')
.contains('researcher user')
Verifying by selectedIndex
cy.get('select#segment_segment_contact_id')
.its('0.selectedIndex')
.should('eq', 1)
You can use this as well. Here first we are getting value of the second item in the list using the eq() command. Then once we have got the value, we are just simply passing that to select().
cy.get('select#segment_segment_contact_id option').eq(1).invoke('val')
.then((val) => {
cy.get('select#segment_segment_contact_id').select(val)
})
And if you want to just validate the value or text you can do:
cy.get('select#segment_segment_contact_id option')
.eq(1).should('have.value', 73349)
cy.get('select#segment_segment_contact_id option')
.eq(1).should('have.text', 'researcher user')
Im trying to get the last clicked option in a multiple select, no matters if the option is selected or unselected.
The problem is that the select is not via template, is mounted dinamically via TS.
I've tried adding vanilla JS event listeners at the creation of the options but doesn't works. Actually i can get all the selected elements, but i lost the unselected option and i can't get exactly the new selected one.
My HTML
<tr *ngFor="let communityLine of communityLines">
<td>{{communityLine.name}}</td>
<td>{{communityLine.instrument.name}}</td>
<td>{{communityLine.param.name}}</td>
<td>{{communityLine.contextSource.name}}</td>
<td>{{communityLine.sampleType.name}}</td>
<td>{{communityLine.value}}</td>
<td>
<select multiple [id] ="communityLine.apiKey" (change)="eventGetChange(communityLine, $event)" [(ngModel)]="nodeKey">
</select>
</td>
</tr>
My TS function
private eventGetChange(commLineKey, event) {
console.log(this.nodeKey);
console.log(commLineKey);
console.log(event.target.value)
My TS method to mount the select, is a bit complicated because i need to show all nodes (stored in this.allNodes var) but select the nodes that are in other array (nodesInRelation var).
private mountSelect(nodesInRelation: Node[], lineApiKey: String): void {
let select = <HTMLSelectElement>document.getElementById(lineApiKey);
let copy = this.allNodes;
for (let node of nodesInRelation) {
copy.forEach((item, index) => {
if (item.name === node.name) copy.splice(index, 1);
});
}
for (let node of nodesInRelation) {
let newoption = new Option(node.name, node.apiKey, null, true);
select.add(newoption);
}
for (let node of copy) {
let newoption = new Option(node.name, node.apiKey, null, false);
select.add(newoption);
}
M.updateTextFields();
M.AutoInit();
}
In eventGetChange function first console.log i get all the current selected values, in the second i get the key and is okey and in the third i get only the first selected element in the box.
I just want the last clicked, selected or unselected.
Thanks you.
You seem to be ditching Angular and opting for direct DOM manipulation for no apparent reason. Angular is perfectly capable of populating options list programmatically. It could look something like
<td>
<select multiple [id] ="communityLine.apiKey" [(ngModel)]="nodeKey">
<option *ngFor="let option of optionList; let i = index"
[value]="option" (click)="eventGetChange(option)">{{ option }}
</option>
</select>
</td>
optionList: any[];
private mountSelect(nodesInRelation: Node[], lineApiKey: String): void {
// populate optionList here
}
private eventGetChange(commLineKey) {
// the clicked option is available here
}
If this.nodeKey as you say stores an array with all the current selected values you can simply do this:
this.nodeKey[this.nodeKey.length - 1]
It will give you the las value in the nodeKey array
We are working on a project where we are using boxes, and need one of the select boxes to perform an action when the user selects an item from the list. This is our first time touching React, let alone building a project, so we are stumped at this point. What we are using for the onChange code is as follows:
var React = require('react');
var ReactPropTypes = React.PropTypes;
var ProgramSelectorComponent = React.createClass({
propTypes: {
allPrograms: ReactPropTypes.array.isRequired
},
_updateProgram: function(e) {
this.setState({
value: "TEST"
});
},
render() {
var Programs = this.props.allPrograms;
var options = Programs.map(function (prog) {
return <option key={ prog.program_id } value={ prog.program_id } >
{ prog.program_name }
</option>;
});
return (
<select className="form-control margin-bottom" name="Program" id="programSelect" ref="progRef" onChange={this._updateProgram} >
<option value="select">Select</option>
{options}
</select>
)
}
});
module.exports = ProgramSelectorComponent;
I know that rendering does work in the <select> tag as I can add something like data-test-id="test" and that renders properly, but for some reason, the onChange is not showing in the code, and therefore, not working.
Like I said, we are all new to this, so any help would be greatly appreciated.
In your select tag try: <select value={this.state.value}>
This is a good read about controlled vs uncontrolled components: https://facebook.github.io/react/docs/forms.html
I have a dynamically created select option using a javascript function. the select object is
<select name="country" id="country">
</select>
when the js function is executed, the "country" object is
<select name="country" id="country">
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
...
<option value="ID">Indonesia</option>
...
<option value="ZW">Zimbabwe</option>
</select>
and displaying "Indonesia" as default selected option. note : there is no selected="selected" attribute in that option.
then I need to set selected="selected" attribute to "Indonesia", and I use this
var country = document.getElementById("country");
country.options[country.options.selectedIndex].setAttribute("selected", "selected");
using firebug, I can see the "Indonesia" option is like this
<option value="ID" selected="selected">Indonesia</option>
but it fails in IE (tested in IE 8).
and then I have tried using jQuery
$( function() {
$("#country option:selected").attr("selected", "selected");
});
it fails both in FFX and IE.
I need the "Indonesia" option to have selected="selected" attribute so when I click reset button, it will select "Indonesia" again.
changing the js function to dynamically create "country" options is not an option. the solution must work both in FFX and IE.
thank you
You're overthinking it:
var country = document.getElementById("country");
country.options[country.options.selectedIndex].selected = true;
Good question. You will need to modify the HTML itself rather than rely on DOM properties.
var opt = $("option[val=ID]"),
html = $("<div>").append(opt.clone()).html();
html = html.replace(/\>/, ' selected="selected">');
opt.replaceWith(html);
The code grabs the option element for Indonesia, clones it and puts it into a new div (not in the document) to retrieve the full HTML string: <option value="ID">Indonesia</option>.
It then does a string replace to add the attribute selected="selected" as a string, before replacing the original option with this new one.
I tested it on IE7. See it with the reset button working properly here: http://jsfiddle.net/XmW49/
Instead of modifying the HTML itself, you should just set the value you want from the relative option element:
$(function() {
$("#country").val("ID");
});
In this case "ID" is the value of the option "Indonesia"
So many wrong answers!
To specify the value that a form field should revert to upon resetting the form, use the following properties:
Checkbox or radio button: defaultChecked
Any other <input> control: defaultValue
Option in a drop down list: defaultSelected
So, to specify the currently selected option as the default:
var country = document.getElementById("country");
country.options[country.selectedIndex].defaultSelected = true;
It may be a good idea to set the defaultSelected value for every option, in case one had previously been set:
var country = document.getElementById("country");
for (var i = 0; i < country.options.length; i++) {
country.options[i].defaultSelected = i == country.selectedIndex;
}
Now, when the form is reset, the selected option will be the one you specified.
// get the OPTION we want selected
var $option = $('#SelectList').children('option[value="'+ id +'"]');
// and now set the option we want selected
$option.attr('selected', true);
What you want to do is set the selectedIndex attribute of the select box.
country.options.selectedIndex = index_of_indonesia;
Changing the 'selected' attribute will generally not work in IE. If you really want the behavior you're describing, I suggest you write a custom javascript reset function to reset all the other values in the form to their default.
This works in FF, IE9
var x = document.getElementById("country").children[2];
x.setAttribute("selected", "selected");
Make option defaultSelected
HTMLOptionElement.defaultSelected = true; // JS
$('selector').prop({defaultSelected: true}); // jQuery
HTMLOptionElement MDN
If the SELECT element is already added to the document (statically or dynamically), to set an option to Attribute-selected and to make it survive a HTMLFormElement.reset() - defaultSelected is used:
const EL_country = document.querySelector('#country');
EL_country.value = 'ID'; // Set SELECT value to 'ID' ("Indonesia")
EL_country.options[EL_country.selectedIndex].defaultSelected = true; // Add Attribute selected to Option Element
document.forms[0].reset(); // "Indonesia" is still selected
<form>
<select name="country" id="country">
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="HR">Croatia</option>
<option value="ID">Indonesia</option>
<option value="ZW">Zimbabwe</option>
</select>
</form>
The above will also work if you build the options dynamically, and than (only afterwards) you want to set one option to be defaultSelected.
const countries = {
AF: 'Afghanistan',
AL: 'Albania',
HR: 'Croatia',
ID: 'Indonesia',
ZW: 'Zimbabwe',
};
const EL_country = document.querySelector('#country');
// (Bad example. Ideally use .createDocumentFragment() and .appendChild() methods)
EL_country.innerHTML = Object.keys(countries).reduce((str, key) => str += `<option value="${key}">${countries[key]}</option>`, '');
EL_country.value = 'ID';
EL_country.options[EL_country.selectedIndex].defaultSelected = true;
document.forms[0].reset(); // "Indonesia" is still selected
<form>
<select name="country" id="country"></select>
</form>
Make option defaultSelected while dynamically creating options
To make an option selected while populating the SELECT Element, use the Option() constructor MDN
var optionElementReference = new Option(text, value, defaultSelected, selected);
const countries = {
AF: 'Afghanistan',
AL: 'Albania',
HR: 'Croatia',
ID: 'Indonesia', // <<< make this one defaultSelected
ZW: 'Zimbabwe',
};
const EL_country = document.querySelector('#country');
const DF_options = document.createDocumentFragment();
Object.keys(countries).forEach(key => {
const isIndonesia = key === 'ID'; // Boolean
DF_options.appendChild(new Option(countries[key], key, isIndonesia, isIndonesia))
});
EL_country.appendChild(DF_options);
document.forms[0].reset(); // "Indonesia" is still selected
<form>
<select name="country" id="country"></select>
</form>
In the demo above Document.createDocumentFragment is used to prevent rendering elements inside the DOM in a loop. Instead, the fragment (containing all the Options) is appended to the Select only once.
SELECT.value vs. OPTION.setAttribute vs. OPTION.selected vs. OPTION.defaultSelected
Although some (older) browsers interpret the OPTION's selected attribute as a "string" state, the WHATWG HTML Specifications html.spec.whatwg.org state that it should represent a Boolean selectedness
The selectedness of an option element is a boolean state, initially false. Except where otherwise specified, when the element is created, its selectedness must be set to true if the element has a selected attribute.
html.spec.whatwg.org - Option selectedness
one can correctly deduce that just the name selected in <option value="foo" selected> is enough to set a truthy state.
Comparison test of the different methods
const EL_select = document.querySelector('#country');
const TPL_options = `
<option value="AF">Afghanistan</option>
<option value="AL">Albania</option>
<option value="HR">Croatia</option>
<option value="ID">Indonesia</option>
<option value="ZW">Zimbabwe</option>
`;
// https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver/MutationObserver
const mutationCB = (mutationsList, observer) => {
mutationsList.forEach(mu => {
const EL = mu.target;
if (mu.type === 'attributes') {
return console.log(`* Attribute ${mu.attributeName} Mutation. ${EL.value}(${EL.text})`);
}
});
};
// (PREPARE SOME TEST FUNCTIONS)
const testOptionsSelectedByProperty = () => {
const test = 'OPTION with Property selected:';
try {
const EL = [...EL_select.options].find(opt => opt.selected);
console.log(`${test} ${EL.value}(${EL.text}) PropSelectedValue: ${EL.selected}`);
} catch (e) {
console.log(`${test} NOT FOUND!`);
}
}
const testOptionsSelectedByAttribute = () => {
const test = 'OPTION with Attribute selected:'
try {
const EL = [...EL_select.options].find(opt => opt.hasAttribute('selected'));
console.log(`${test} ${EL.value}(${EL.text}) AttrSelectedValue: ${EL.getAttribute('selected')}`);
} catch (e) {
console.log(`${test} NOT FOUND!`);
}
}
const testSelect = () => {
console.log(`SELECT value:${EL_select.value} selectedIndex:${EL_select.selectedIndex}`);
}
const formReset = () => {
EL_select.value = '';
EL_select.innerHTML = TPL_options;
// Attach MutationObserver to every Option to track if Attribute will change
[...EL_select.options].forEach(EL_option => {
const observer = new MutationObserver(mutationCB);
observer.observe(EL_option, {attributes: true});
});
}
// -----------
// LET'S TEST!
console.log('\n1. Set SELECT value');
formReset();
EL_select.value = 'AL'; // Constatation: MutationObserver did NOT triggered!!!!
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
console.log('\n2. Set HTMLElement.setAttribute()');
formReset();
EL_select.options[2].setAttribute('selected', true); // MutationObserver triggers
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
console.log('\n3. Set HTMLOptionElement.defaultSelected');
formReset();
EL_select.options[3].defaultSelected = true; // MutationObserver triggers
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
console.log('\n4. Set SELECT value and HTMLOptionElement.defaultSelected');
formReset();
EL_select.value = 'ZW'
EL_select.options[EL_select.selectedIndex].defaultSelected = true; // MutationObserver triggers
testOptionsSelectedByProperty();
testOptionsSelectedByAttribute();
testSelect();
/* END */
console.log('\n*. Getting MutationObservers out from call-stack...');
<form>
<select name="country" id="country"></select>
</form>
Although the test 2. using .setAttribute() seems at first the best solution since both the Element Property and Attribute are unison, it can lead to confusion, specially because .setAttribute expects two parameters:
EL_select.options[1].setAttribute('selected', false);
// <option value="AL" selected="false"> // But still selected!
will actually make the option selected
Should one use .removeAttribute() or perhaps .setAttribute('selected', ???) to another value? Or should one read the state by using .getAttribute('selected') or by using .hasAttribute('selected')?
Instead test 3. (and 4.) using defaultSelected gives the expected results:
Attribute selected as a named Selectedness state.
Property selected on the Element Object, with a Boolean value.
select = document.getElementById('selectId');
var opt = document.createElement('option');
opt.value = 'value';
opt.innerHTML = 'name';
opt.selected = true;
select.appendChild(opt);
// Get <select> object
var sel = $('country');
// Loop through and look for value match, then break
for(i=0;i<sel.length;i++) { if(sel.value=="ID") { break; } }
// Select index
sel.options.selectedIndex = i;
Begitu loh.
This should work.
$("#country [value='ID']").attr("selected","selected");
If you have function calls bound to the element just follow it with something like
$("#country").change();
You could search all the option values until it finds the correct one.
var defaultVal = "Country";
$("#select").find("option").each(function () {
if ($(this).val() == defaultVal) {
$(this).prop("selected", "selected");
}
});
Vanilla JS
Use this for Vanilla Javascript, keeping in mind that you can feed the example "numbers" array with any data from a fetch function (for example).
The initial HTML code:
<label for="the_selection">
<select name="the_selection" id="the_selection_id">
<!-- Empty Selection -->
</select>
</label>
Some values select tag:
const selectionList = document.getElementById('the_selection_id');
const numbers = ['1','3','5'];
numbers.forEach(number => {
const someOption = document.createElement('option');
someOption.setAttribute('value', number);
someOption.innerText = number;
if (number == '3') someOption.defaultSelected = true;
selectionList.appendChild(someOption);
})
You'll get:
<label for="the_selection">
<select name="the_selection" id="the_selection_id">
<!-- Empty Selection -->
<option value="1">1</option>
<option value="3" selected>3</option>
<option value="5">5</option>
</select>
</label>
You can solve this on ES6 like this:
var defaultValue = "ID";
[...document.getElementById('country').options].map(e => e.selected = (e.value == defaultValue));
I haven't test in other browsers but in Chrome works just fine.
...document.getElementById('country').options using the spread operator you cast options as an array.
.map allows you to apply a function to each element of your array.
e represents each <option> element of your object so you can access its attributes like .select and .value as getter and setter.
Because you .select receives a boolean option you want to assign when its value is equal to your default value.
To set the input option at run time try setting the 'checked' value. (even if it isn't a checkbox)
elem.checked=true;
Where elem is a reference to the option to be selected.
So for the above issue:
var country = document.getElementById("country");
country.options[country.options.selectedIndex].checked=true;
This works for me, even when the options are not wrapped in a .
If all of the tags share the same name, they should uncheck when the new one is checked.
Realize this is an old question, but with the newer version of JQuery you can now do the following:
$("option[val=ID]").prop("selected",true);
This accomplishes the same thing as Box9's selected answer in one line.
The ideas on this page were helpful, yet as ever my scenario was different. So, in modal bootstrap / express node js / aws beanstalk, this worked for me:
var modal = $(this);
modal.find(".modal-body select#cJourney").val(vcJourney).attr("selected","selected");
Where my select ID = "cJourney" and the drop down value was stored in variable: vcJourney
I was trying something like this using the $(...).val() function, but the function did not exist. It turns out that you can manually set the value the same way you do it for an <input>:
// Set value to Indonesia ("ID"):
$('#country').value = 'ID'
...and it get's automatically updated in the select. Works on Firefox at least; you might want to try it out in the others.
To set value in JavaScript using set attribute , for selected option tag
var newvalue = 10;
var x = document.getElementById("optionid").selectedIndex;
document.getElementById("optionid")[x].setAttribute('value', newvalue);