andrelange91
andrelange91

Reputation: 1188

get data attribute and set new value

I cannot get my code to work..

i select my elements, and try to get the value of a data attribute, and change the value accordingly.

Html:

<div class="flipUpMenu" id="flipUpMenuBox" data-flip="false"></div>
<button id="flipElement">Flip Up </button>

JS:

$( document ).ready(function() {
    //buttons
    var btnFlip = $("#flipElement");

    //elements
    var flipUpElement = $("flipUpMenuBox");

    btnFlip.click(function(){
        if(flipUpElement.data('flip') === 'false'){
            alert("flip true");
        }else{
            alert("flip false");
        }
    });
});

Instead of alerts, i would want to set the data-flip to either true or false. As a way of toggleing it.

Upvotes: 1

Views: 3594

Answers (3)

Barmar
Barmar

Reputation: 782529

if(flipUpElement.data('flip') === 'false'){

won't work as intended. jQuery .data() tries to parse the data attribute as JSON, and if that succeeds it returns the parsed value. So "false" will be converted to a boolean false instead of returning the string.

So you should change it to:

if(flipUpElement.data('flip')) {
    flipUpElement.data('flip', false);
} else {
    flipUpElement.data('flip', true);
}

or more simply:

flipUpElement.data('flip', !flipUpElement.data('flip'));

And as others have pointed out, you left out the # in the selector used to set flipUpElement.

Upvotes: 0

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72269

$("flipUpMenuBox") need to be $("#flipUpMenuBox")

Working snippet:-

$( document ).ready(function() {
  var btnFlip = $("#flipElement");
  var flipUpElement = $("#flipUpMenuBox");
  btnFlip.click(function(){
    if(flipUpElement.attr('data-flip') == 'false'){ // use ==
      flipUpElement.attr('data-flip','true');
    }else{
      flipUpElement.attr('data-flip','false');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flipUpMenu" id="flipUpMenuBox" data-flip="false"></div>
<button id="flipElement">Flip Up </button>

Upvotes: 1

The Alpha
The Alpha

Reputation: 146269

You can use the following:

// Select the element by id

var flipUpElement = $("#flipUpMenuBox");

// Set the data

flipUpElement.data('flip', true);

// Get the data and log it

console.log(flipUpElement.data('flip'));

$(document).ready(function() {
    var flipUpElement = $("#flipUpMenuBox");
    flipUpElement.data('flip', true);
    console.log(flipUpElement.data('flip'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flipUpMenu" id="flipUpMenuBox" data-flip="false"></div>

Also, make sure you've used $("#flipUpMenuBox") not $("flipUpMenuBox") to select the element, I can see you've used $("flipUpMenuBox").

Upvotes: 2

Related Questions