Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.hide() is not a function error when executing from a loop

I want to be able to loop over a few different labels and hide their content based on if a radio button is check or not. This is the solution I came up with, but I keep getting an error in the console.

var hazardOptions = $(".js-hazardous-option");
var hazard = $("input[name=Hazardous]");
for (var i = 0, len = hazard.length; i < len; i++) {
    if (hazard[i].id === "HazardousYes" && hazard[i].checked) {
        for (var ii = 0, length = hazardOptions.length; ii < length; ii++) {
            hazardOptions[ii].show();
        }
    } else if (hazard[i].id === "HazardousNo" && hazard[i].checked) {
        for (var iii = 0, leng = hazardOptions.length; iii < leng; iii++) {
            hazardOptions[iii].hide();
        }
    }
}

The error I get is:

hide() is not a function

Not sure what I'm missing, I've tried having a look online for a similar issue, but with no luck. I'm pretty sure that the problem is here: hazardOptions[iii].hide(); but not really sure why and/or how to fix it.

like image 827
Web Develop Wolf Avatar asked Jan 30 '23 19:01

Web Develop Wolf


1 Answers

When you have a list of objects from a JQuery selector, if you try to access them via index you actually get the DOM element back and not the JQuery object. It's confusing for sure but it is in the documentation.

What you effectively need to do is turn it back into a JQuery object:

$(hazardOptions[iii]).hide();

Or you can use the eq() function with does provide the JQuery object ad thus still has the hide() function:

hazardOptions.eq(iii).hide();
like image 118
musefan Avatar answered Feb 03 '23 08:02

musefan