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);
}
getusually implies that it returns a value without modifying anything. Yourgetfunctions actually perform a change on the page when called and don't return anything, which is rather counter-intuitive. Also, all your variables could be constants.const direction = (sortDirection === 'desc') ? -1 : 1;