-1

I have a sort of a niche case here.

So I'm building out a sidebar tool to utilize for quick note-taking, and I'm running into a problem without setting hundreds of data-attrs.

Currently, I have a dropdown menu that displays content that contains a specific data-attr based on the selection and hides the rest. The problem I'm encountering is I also want it to display all items that do not contain any data-attrs.

Is there a simple way to check if an item has no HTML defined data sets?

HTML:

<select id="ouSelect">
  <option></option>
  <option data-ou="aiv">AIV ***</option>    
  <option data-ou="appstore">Appstore ***</option>
  <option data-ou="firetv">Fire TV ***</option>
  <option data-ou="kindle">Kindle ***</option>
</select>

<ul id="stuffs">
  <li data-kindle="true">Kindle</li>
  <li>Generic</li>
  <li data-aiv="true">AIV</li>
  <li>Generic</li>
  <li data-firetv="true">FireTV</li>
  <li>Generic</li>
  <li data-appstore="true">Appstore</li>
  <li>Generic</li>
</ul>

jQuery:

$(function(){
  var ou = "";
  $('#ouSelect').change(function() {
    ou = $('#ouSelect option:selected').data('ou');
    ouSelected(ou);
  });
  function ouSelected(which){
    $('li').each(function(){
      if($(this).data(which) === undefined){
        $(this).hide();
      } else {
        $(this).show();
      }
    })
  }
});

CodePen: http://codepen.io/anon/pen/GyqoK

As you can see, all of the generic sets disappear when an option is selected. Ideally I'd want the items with data-kindle to display as well as items with no data-attrs at all.

Any ideas how to accomplish this? Any help is appreciated!

Nicholas Hazel
  • 3,758
  • 1
  • 22
  • 34
  • you found your answer [here](http://stackoverflow.com/questions/1894792/determining-if-a-javascript-object-has-a-given-property) – Claudio Santos Jul 24 '14 at 18:35

2 Answers2

2

Change your check to this:

if($(this).data(which) === undefined && Object.keys($(this).data()).length > 0)
juvian
  • 15,875
  • 2
  • 37
  • 38
0

Given support for the dataset property, it’s as easy as:

Object.keys(element.dataset).length === 0

That’s not really appropriate, though. data-* attributes aren’t meant to interfere with each other, and they shouldn’t have dynamic names. How about identifying categories in a simpler way?

<li data-category="appstore">Appstore</li>

(Not given support for the dataset property, you can use

function hasDataAttributes(element) {
    for (var i = 0; i < element.attributes.length; i++) {
        var name = element.attributes[i].name;

        if (name.substring(0, 5) === 'data-') {
            return true;
        }
    }

    return false;
}

.)

Ry-
  • 218,210
  • 55
  • 464
  • 476