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.
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
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
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
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With