0

My code doesn't seem to access the data attribute name and I have tried many different codes.

<div class="columns offer_table_rows" style=" position:relative;" data-personal="1" data-euro="" data-vehicle="122" data-roadside="neutral false " data-national="neutral false " data-home="neutral  true" data-onward="neutral  true" data-name="Different Brand 1">
$(".brandName").on('click', function() {
  $wrapper.find('.offer_table_rows').sort(function(a, b) {
    return $(a).dataset('name').toLowerCase() > $(b).dataset('name').toLowerCase();
  }).appendTo($wrapper);
})

$wrapper.find('.offer_table_rows').sort(function(a, b) {
  return b.dataset.name - a.dataset.name;
})

When the brandName filter button is clicked the wrapper div finds a row and sorts using data attribute name. I've tried both of the above variations but none seem to access the data attribute, or I just don't know what is going wrong.

I know for sure the wrapper finds the row and it all works until the data attribute is searched, as I have number sorts that do work with the same code.

Edit

This is not a duplicate as the proposed answer doesn't answer this question. Using $(a).data instead of what I have doesn't work. I am able to console.log the data names if I use console.log($(a).data('name')) but they don't seem to sort.

Edit 2

I can console.log true false when evaluating if data.a is bigger than data.b:

`$(".brandName").on('click', function() { $wrapper.find('.offer_table_rows').sort(function(a, b) { // console.log(a.dataset.name >b.dataset.name); })   }) 

But if I try to make it a function that returns and appends to the wrapper it does nothing.

halfer
  • 19,824
  • 17
  • 99
  • 186
Chris Cullen
  • 110
  • 9

1 Answers1

0

Use localeCompare

.sort((a, b) => a.localeCompare(b));

dddenis
  • 480
  • 1
  • 8
  • 14
  • 1
    `a` and `b` are Element objects, not strings. – Rory McCrossan Jan 03 '19 at 11:53
  • `$(".brandName").on('click', function() { $wrapper.find('.offer_table_rows').sort(function(a, b) { var x = a.dataset.name.toLowerCase(); var y = b.dataset.name.toLowerCase(); if (x < y) {return -1;} if (x > y) {return 1;} return 0; }).appendTo($wrapper); })` This is a Working answer – Chris Cullen Jan 04 '19 at 17:19