Wrong Assumption
Attribute/Properties as Defaults
At first I thought this question was trivial because I naturally assumed that any attribute/property bestowed on a tag would show up easily since its just something that confirms a "state" to which an element is obviously in (ex. a checkbox is checked by a user, so there's no need to use .setAttribute()
on it so it has the checked
attribute because it should already have it by default.)
My assumption was wrong, attributes like checked
, selected
, disabled
, etc are on a tag to set an initial "state" by default. So these attributes/properties do not magically manifest when a user checks a checkbox or selects on <option>
from a <select>
element. The two most effective ways to handle these attribute/properties is to:
Plain JavaScript
Use set
/get
/remove
/hasAttribute()
method family.
jQuery
Use .prop()
/.removeProp()
method, do not use .attr()
Solution
The following section discusses important parts of the Demo that follows:
var s = sel.options[sel.selectedIndex];
There's two parts to this assignment:
This s a HTMLOptionsCollection which is similar to a NodeList of an array-like Object.
.options
The second half is a property that is unique to <select>
and <option>
tags:
.selectedIndex
On its own it returns an index number of the first selected <option>
of a given <select>
, but in combination with the formerly mentioned .options
Object, we have a very formidable tool to access a <select>
, locate the selected <option>
, and retrieve it as a useful DOM Object instead of an index number.
The rest of the demo uses a for()
loop, Array.prototype.push()
, .setAttribute()
, .removeAttribute()
. Almost forgot that the jQuery function listened for a "change" event occuring on the <select>
:
$('select').on('change', function(e) {...
Demo
Details are commented in the demo on every line
// Listen for change events on a <select>
var s = $('select').on('change', function(sel) {
// Empty array
var sArr = [];
// Dereferenced jQuery Object
var sel = $('select')[0];
// options HTMLCollection with a selectedIndex property
var s = sel.options[sel.selectedIndex];
// Total number of loops
var sL = sel.length;
// for() loop
for (let S = 0; S < sL; S++) {
// On each loop a selected attr is removed from each option
sel[S].removeAttribute('selected');
// The empty array is loaded with only the first 3 loops
if (S < 3) {
sArr.push(sel[S]);
}
}
// One option from the 3 in the short array gets a selected attr
s.setAttribute('selected', 'selected');
// Clear console
console.clear();
// Display selected option
console.log(s);
// Display all 3 options from the short array
console.log(sArr);
});
.as-console-row-code {
color: gold;
background: #000;
font-size: 21px;
}
.as-console-row {
color: gold;
background: #000;
max-width: 15px;
}
<select>
<option> jQuery </option>
<option> JavaScript </option>
<option> CSS </option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>