Reputation: 458
I have an select bar with a few options where I am trying to sort some things and I am also trying to implement, that if you click the option again then it will switch to ascending or descending order.
I have this HTML elements:
<select name="theme" id="sortSelect">
<option> -
</option>
<option value="firstName" data-sort-direction="asc">First Name
</option>
<option value="lastName" data-sort-direction="asc">Last Name
</option>
<option value="house" data-sort-direction="asc">House
</option>
</select>
I get the value in JavaScript by using this keyword, I have added an event listener to listen for a 'change' and that leads to a function and inside that function I'm getting the value like this: const selectedValue = this.value;
that works totally fine but when I try to get the data-sort-direction='asc'
in JavaScript like this: let sortDirection = this.dataset.sortDirection;
then it returns undefined. What am I doing wrong here? help would be much appreciated!
edit: these are the 2 functions that I'm using:
function getSortedValues() {
const selectedValue = this.value;
let sortDirection = this.dataset.sortDirection;
if (sortDirection === 'asc') {
this.dataset.sortDirection = 'desc';
} else {
this.dataset.sortDirection = 'asc';
}
console.log(sortDirection);
getSortedStudent(selectedValue, sortDirection);
}
function getSortedStudent(pressedValue, sortDirection) {
let sortedStudents = [];
let direction = 1;
if (sortDirection === 'desc') {
direction = -1;
} else {
sortDirection = 1;
}
sortedStudents = allStudents.sort((a, b) => {
if (a[pressedValue] < b[pressedValue]) {
return -1 * direction;
} else {
return 1 * direction;
}
});
displayList(sortedStudents);
}
Upvotes: 1
Views: 717
Reputation: 2675
As mentioned in @Tim Lewis's answer, the select value attribute changes, but nothing else from <option>
is carried over. There are a lot of ways to find the selected item with radios, checkbox, or dropdowns, but my preferred method is the :checked
pseudo selector. Here's an example.
var select = document.querySelector('#sortSelect')
select.addEventListener('change', function(e) {
var selectedOption = document.querySelector('option:checked')
console.log(this.value, selectedOption.dataset);
})
<select name="theme" id="sortSelect">
<option> -
</option>
<option value="firstName" data-sort-direction="asc">First Name
</option>
<option value="lastName" data-sort-direction="asc">Last Name
</option>
<option value="house" data-sort-direction="asc">House
</option>
</select>
Upvotes: 2
Reputation: 29316
this.dataset
is the data
attributes of the <select>
, not the <option>
. You can get that via:
let sortDirection = this.options[this.selectedIndex].dataset.sortDirection;
Note, this may still be undefined
, as your initial option doesn't have a data-sort-direction
attribute.
Upvotes: 6