Mahmood Mahmood -4 years ago 79
Javascript Question

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).

Answer Source

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();
        }   
    });
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download