Nick Res
Nick Res

Reputation: 2244

Why is jQuery not adding the data attribute to this element?

I have a hidden modal box on my page that gets rendered with the call of this create.js file.

Everything else is working nicely except for adding a data-meal_id attribute to the element.

Here's the jquery:

var $modal, $modal_close, $modal_container, $meal_id;
$modal = $('#modal');
$modal_close = $modal.find('.close');
$modal_container = $('#modal-container');
$meal_id = <%= @meal_id %>

$modal
  .data('meal_id', $meal_id)
  .prepend($modal_close)
  .css('top', $(window)
  .scrollTop() + 100)
  .show();

$modal_container.show();

$(document).on('click', '#modal .close', function() {
  $modal_container.hide();
  $modal.hide();
  return false;
});       

Here are the elements before the above code is triggered:

<div id="modal-container"></div>
<div id="modal">

After being triggered...

<div id="modal-container" style="display: block;"></div>
<div id="modal" style="top: 100px; display: block;"><a href="#" class="close">cancel</a>

Totally skips the data attribute??!

Upvotes: 3

Views: 343

Answers (1)

Musa
Musa

Reputation: 97672

The .data() method does not modify the dom if you want to set a data attribute of an element you'll have to use attr()

$modal
  .attr('data-meal_id', $meal_id)

Upvotes: 8

Related Questions