Danielle Rose Mabunga Danielle Rose Mabunga - 4 months ago 67
jQuery Question

Get widget data attribute in Gridster

I want to get the data attributes per widget in gridster.js.

draggable: {
stop: function(event, ui) {
var positions = JSON.stringify(this.serialize());
var att = $(".gridster ul li").attr('data-id');
alert(att);
//localStorage.setItem('positions', positions);
//console.log(positions);
$.ajax ({
url: '/partA-save-widgets-positions',
type: 'POST',
data: {
'positions': positions
},
dataType: 'JSON',
error: function(log) {
console.log(log);
},
success: function(log) {
console.log(log);
}
})
}


html

<div class="gridster">
<ul>
@foreach($widgets as $wi)
<li data-row="2" data-id="7">values</li>
@endforeach
</ul>
</div>


using

var att = $(".gridster ul li").attr('data-id');
alert(att); //undefined

Answer

You can use the ui variable here to achieve this like:-

var att = $(ui.$helper[0]).attr('data-row'); 
alert(att);

As a suggestion, you can always debug the code yourself using the console.log() and checking what the ui variable is actually pointing to and debug more to find the object properties it have and then find that current element being dragged, as we have discussed in the comments above like:

draggable: {
  stop: function(event, ui) {
    console.log(ui);  // check the properties here
    console.log(ui.$helper);  // check other properties inside ui
    console.log($(ui.$helper[0]).attr('data-id'));  // final required value
  }
}

Hope this helps the furture users having the same issue while using draggable or any other jquery ui widgets!

Comments