简体   繁体   中英

jQuery.each not running in function

I'm working on a project where some form elements depend on another form input to have a certain value, or possibly multiple elements with specific values before that input is shown.

The idea is that when the form is generated, the wrapping div for each input has a data-depends-on attribute with a comma-separated list of each field that it depends on to be shown, and the values for each that it's expecting to be shown.

I almost have the front-end / JavaScript code down to do the lifting, but for some reason my jQuery.each() loop in a JavaScript function isn't running even though I've confirmed the array I'm trying to loop through a. has content, and b. that the functioning is actually being called when it is expected to do so.

First, I have the actual function call (which is called whenever a dependency input is changed):

checkShowField(keyed_depends, current_vals, targeted_element);

And then the function checkShowField() definition:

function checkShowField(keyed_dependencies, current_values, targeted_element)
{
    var hide_field = null;
    jQuery.each(keyed_dependencies, function(key, value)
    {
        if (value != current_values[key] && hide_field == null)
            hide_field = false;
    });

    if (hide_field == null)
        $(targeted_element).slideDown();
    else
        $(targeted_element).slideUp();
}

Also please note that the function call is placed in the proper place, and is actually being called. I just added the code on here to show everyone context of how the function is being called. The function call is wrapped in $(document).ready(function() {...}.

So as you can see, in the function "checkShowField", I have a jQuery.each loop that should be looping through keyed_dependencies array, but in actuality, the loop isn't even running once. Thoughts?

It looks like the keyed_dependencies is not really what you think it is. Try adding debugger; statements before the .each line and maybe in the function as well. Then use inspector/debugger to review the data in the variables.

You can check, if keyed_dependencies in argument list has a property length . If so, jQuery assumes an array and might actually fail to run you loop.

If that is the case, try using vanilla JS:

for (var key in keyed_dependencies) {...}

Hope that helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM