Mahmood
Mahmood

Reputation: 177

Two jQuery functions not working in single <script> tag

I have a requirement,

  1. on selection of a particular picklist item, I need to show/hide a section with checkbox
  2. on selection of the checkbox, in step-1, I further need to show/hide another section.

This is what I tried

<script>
j$('#type').on('change', function()
{

    if(this.value == 'Technical Issue'){ 
        j$('#techtroubleshootoption').show();
         j$('#forceemailcase').show();
        j$('#main').hide();
    } 
    else{
        j$('#techtroubleshootoption').hide();
        j$('#forceemailcase').hide();
        j$('#main').show();
    } 
});
j$('#chkforcemailcase').click( function()
{
  if(this.checked){ 
        j$('#techtroubleshootoption').hide();
         j$('#forceemailcase').show();
        j$('#main').show();
    } 
    else{
        j$('#techtroubleshootoption').show();
        j$('#forceemailcase').show();
        j$('#main').hide();
    }   
});
</script>

The first function is working and upon selection of a desired values it is showing/hiding section below, but on the selection of checkbox, it is not doing anything.

Workaround

If a put the second function in another <script> tag it works fine. Now, my question is why it didn't work in the same <script> tag and is it the right way to do it to declare multiple <script> tags for each function (which doesn't sound right to me).

Upvotes: 0

Views: 166

Answers (2)

Joshua Russell
Joshua Russell

Reputation: 700

You need to wrap all of your javascript with $(document).ready()

$(document).ready(function() {

    j$('#type').on('change', function() {
        if(this.value == 'Technical Issue'){ 
            j$('#techtroubleshootoption').show();
                j$('#forceemailcase').show();
            j$('#main').hide();
        } 
        else{
            j$('#techtroubleshootoption').hide();
            j$('#forceemailcase').hide();
            j$('#main').show();
        } 
        });
        j$('#chkforcemailcase').click( function()
        {
        if(this.checked){ 
            j$('#techtroubleshootoption').hide();
                j$('#forceemailcase').show();
            j$('#main').show();
        } 
        else{
            j$('#techtroubleshootoption').show();
            j$('#forceemailcase').show();
            j$('#main').hide();
        }   
    });
});

Upvotes: 1

Steve Harris
Steve Harris

Reputation: 306

If you are initializing events, you should do that when the document is ready, not in script tags directly. script tags are generally a race condition when it comes to elements being available in the DOM while it is being rendered.

Use $(document).ready().

Upvotes: 1

Related Questions