Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery.data(key) throwing undefined is not a function

Tags:

I have some checkboxes which are used to show/hide columns and automatically resize them to fit the screen. I've linked the checkboxes to their relevent columns using a data attribute and try to read this value using jQuery.data(). This gives an error of "undefined is not a function" even though a breakpoint seems to show I have set my variables up properly up to this point.

HTML

<div class="col-xs-12">
    <span>Show or hide columns:</span>
    <input type="checkbox" checked="checked" id="column-selector" data-column="selectioncolumn" />Selection via dropdowns
    <input type="checkbox" checked="checked" id="column-selector" data-column="listcolumn" />Selected items
    <input type="checkbox" checked="checked" id="column-selector" data-column="mapcolumn" />Map
</div>

<div id="selectioncolumn" class="col-xs-4">
    Div 1
</div>
<div id="listcolumn" class="col-xs-4">
    Div 2
</div>
<div id="mapcolumn" class="col-xs-4">
    Div 3
</div>

jQuery

$(document).ready(function () {
    $('#column-selector').on('change', function () {
        var numberOfColumns = $('#column-selector:checked').length;
        var sizeOfVisibleColumn = numberOfColumns === 0 ? 4 : 12 / numberOfColumns;
        var columnClass = 'col-xs-' + sizeOfVisibleColumn;
        $.each($('#column-selector'), function (i, checkbox) {
            var columnId = checkbox.data('column'); //Error occurs here
            //More stuff
        });
    });
});

by setting a breakpoint I can see that the attribute has been set and the dataset populated.

attribute and dataset values

However, the line var columnId = checkbox.data('column'); leads to the error "Uncaught TypeError: undefined is not a function". What have I done wrong?

JSFiddle

JQuery version is 2.1.1 browser is Chrome 40.0.2214.111 m

like image 630
Andy Nichols Avatar asked Feb 16 '15 10:02

Andy Nichols


2 Answers

You need convert checkbox(which is DOMElement) to jQuery Object

var columnId = $(checkbox).data('column');

Change checkbox.prop('checked') to $(checkbox).prop('checked')

Also in your example there are three elements with same id (id="column-selector"), I've changed to class (class="column-selector"), because id must be unique

Example

like image 74
Oleksandr T. Avatar answered Oct 25 '22 01:10

Oleksandr T.


You need to cast checkbox to a jQuery element:

 $.each($('#column-selector'), function (i, checkbox) {
    var columnId = $(checkbox).data('column'); //Error occurs here
    //More stuff
 });
like image 45
Beri Avatar answered Oct 25 '22 02:10

Beri