Question

I'm in the process of making dynamic forms using jQuery. I just got it to work on a simple level, and realized that I may be going about it wrong. The code I have works after I change the form value (as you may expect), but it does not work when I first load the page:

jQuery ->
    $(document).ready ->
        $("#subject_enrolled").change ->
            if ($("#subject_enrolled").val() is "0")
                $("#subject_reason_not_enrolled").show()    
            else
                $("#subject_reason_not_enrolled").hide()
            return
        return
    return

I tried .live instead of .change (knowing that it would be a performance hit), but it didn't work anyway. So I'm curious on the next step. I figure I have to define a function that keeps track of states, and add state variables to every conditional select/check box. Is this the best approach? I was hoping I would be able to compute all the changes via jQuery...but I'm starting to think that's bad form.

Was it helpful?

Solution

To run code right after page load make a function that checks conditions, for example:

toggleField = ->
    if $("#subject_enrolled").val() is "0"
        $("#subject_reason_not_enrolled").show()
    else
       $("#subject_reason_not_enrolled").hide()
    return

jQuery ->
    $(document).ready ->
        /**
         * Execute after load
         */
        toggleField()
        $("#subject_enrolled").on "change", ->
            /**
             * Execute after change
             */
            toggleField()
            return
        return
    return
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top