0

In Rails I have a form which edit multiple records at a time. I want to show some elements only if a checkbox is ticked. Here's the javascript I wrote :

<script type="text/javascript">
    $(document).ready(function() {

        // Initially if free is checked hide nonfree options else show
        if ($('<%= "#submits_#{submitid}_free" %>').attr('value') == '1') {
            $('<%= "#submits_#{submitid}_revealnonfree" %>').hide();
        } else {
            $('<%= "#submits_#{submitid}_revealnonfree" %>').show();
        }

        // Initiall if sell rights is checked show prices or else hide
        if ($('<%= "#submits_#{submitid}_sellrights" %>').attr('value') == '1') {
            $('<%= "#submits_#{submitid}_revealrights" %>').show();
        } else {
            $('<%= "#submits_#{submitid}_revealrights" %>').hide();
        }

        // If free checked hide nonfree
        $('<%= "#submits_#{submitid}_free" %>').change(function() {
            if (this.checked) {
                $('<%= "#submits_#{submitid}_revealnonfree" %>').fadeOut('slow');
            } else {
                $('<%= "#submits_#{submitid}_revealnonfree" %>').fadeIn('slow');
            }
        });

        //If sell rights checked show prices
        $('<%= "#submits_#{submitid}_sellrights" %>').change(function() {
            if (this.checked) {
                $('<%= "#submits_#{submitid}_revealrights" %>').fadeIn('slow');
            } else {
                $('<%= "#submits_#{submitid}_revealrights" %>').fadeOut('slow');
            }
        });

    });
</script>

I load it after every record. The script does hide and unhide elements when the correct check box values are changed. But if the checkbox is ticked on the beginning when the page loads, the script won't show the necessary elements. The first part of the script should do that but it doesn't. Here's my form source code without the scripts : http://pastebin.com/Vj9HbrEB

1 Answer 1

1

Simply trigger the change event once for each checkbox, ad this to the end of your script:

    $('<%= "#submits_#{submitid}_free" %>').trigger('change')
    $('<%= "#submits_#{submitid}_sellrights" %>').trigger('change')
Sign up to request clarification or add additional context in comments.

2 Comments

It should work, can you pop a console.log in your on change listener and make sure my two lines are after the change listeners are added?
Yes it worked! I have accidentally placed it after document.ready function. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.