Skip to content Skip to sidebar Skip to footer

Jquery Error: $("[data-weight]") Is Null

Stripped a ton of stuff to make it more readable, it throws an error on the line: $('[data-weight]').each(function() { Saying that it is null

Solution 1:

If you're using jQuery's "no conflict" mode, the problem might be this:

jQuery(document).ready(function() {
                                ^-- Consider adding $ here

...or use jQuery rather than $ throughout.

If you're not using jQuery no-conflict, I'm not seeing why there'd be a problem. It works just fine here: http://jsbin.com/odaxa3 The only edits I made were to load jQuery from Google's CDN and to make the weight in the attribute match the display.

Solution 2:

data-weight is not a valid attribute, on before HTML5. How about doing it this way,

html part,

<strongclass="weight-800">800 KG</strong>

jQuery part,

jQuery(document).ready(function () {
    $('[class^="weight"]').each(function () {

        var usingMetric = false;

        var $this = $(this);
        var value = this.className.split('-')[1];
        if (usingMetric) {
            $this.text(value + " KG");
        }
        else {
            value = parseFloat(value) * 2.20462262; // Convert to imperial
            $this.text(value + " lbs");
        }
    });
});

demo

Solution 3:

Instead of converting the units, you could print all units and only display the one that is preferred:

<strong><spanclass="metric">800 kg</span><spanclass="units-separator">/</span><spanclass="imperial">1763 lbs</span></strong>

Now you can switch between the units by displaying/hiding the elements with the class metric‍/‍imperial:

.units-separator { display: none }
/* for metric view */.metric { }
.imperial { display: none }
/* for imperial view */.metric { display: none }
.imperial { }

And if CSS is not supported, both units are shown as:

800 kg / 1763 lbs

Solution 4:

May i know,what is 'data-weight' ? Is it a control ID? If it is control id then you need to give :

$('#data-weight').children().each(function() {...

Or

The following post might be helpful to you :

jQuery attribute selectors: How to query for an attribute with a custom namespace

Post a Comment for "Jquery Error: $("[data-weight]") Is Null"