DanilGholtsman
DanilGholtsman

Reputation: 2374

Page freezes after js function called once

On my page I got checkbox. If it's checked then we set input fields enable else they disabled. So when I load page first time it works okay. But after it's just freezes. In Chrome console seems that there are nothing appears.

Why could it be?

So heres the element

<label  class="switch span2">
        <input id="p_switcher" name="action" type="checkbox" class="switch-input"/>
        <span class="switch-label" data-on="New Project" data-off="Open Project"></span>
        <span class="switch-handle"></span> 
</label>

fileds looks like that (as example)

<input type="text" name="ProjectName" placeholder="Project Name" id="textProjectName" disabled/>

heres the JS

    <script type="text/javascript">
        $(function () {
            // disable not usable fileds 
            var handlers = function () {
                $('input#p_switcher').change(function () {
                    //setting the atributes 
                    var setAttr = function (fieldName, value) {
                        $('[name=' + fieldName + ']').attr('disabled', value);
                        w2ui.form.fields.filter(function (x) { return x.name == fieldName; })[0].required = !value;
                    }                
                    if ($('input#p_switcher').prop("checked", true)) {
                     //   setAttr('projectId', true);
                        setAttr('ProjectName', false);
                        setAttr('CompanyName', false);
                        setAttr('FieldOperator', false);
                        setAttr('FieldName', false);
                        setAttr('Unit', false);
                    } else {
                     //   setAttr('projectId', false);
                        setAttr('ProjectName', true);
                        setAttr('CompanyName', true);
                        setAttr('FieldOperator', true);
                        setAttr('FieldName', true);
                        setAttr('Unit', true);
                    }

                    w2ui.form.refresh();
                    handlers();
                });
            }

            setTimeout(handlers, 500);   
       });
</script>

Upvotes: 0

Views: 82

Answers (2)

philipp
philipp

Reputation: 16515

I guess this is it… You are calling handler from within handler, without timeout…

$(function () {
        // disable not usable fileds 
        /*
         * shortened
         */

                //recursion, no timeout
                handlers();
            });
        }

        setTimeout(handlers, 500);   
   });

Upvotes: 2

CodingIntrigue
CodingIntrigue

Reputation: 78525

if ($('input#p_switcher').prop("checked", true)) {

On this line you are essentially triggering the .change event again.

I think you mean:

if($('input#p_switcher').prop("checked")) {
    ....
}

Upvotes: 2

Related Questions