Search code examples
javascriptjqueryhtmlonchangeselectionchanged

onChange not working to show/hide a div


I have a piece of code with HTML & JavaScript.

HTML code is

<select name="paytype" id="paytype" onchange="insProviderTable()">
            <option value="Cash">Cash</option>
            <option value="Credit" selected>Credit</option>
        </select>

<div id="insuranceDetails" style="display:none">
    BULB
</div>

and JavaScript code is

function insProviderTable() {   
        if ($('#paytype').val() == 'Credit') {
            $('#insuranceDetails').show(1000);
        }
        else {
            $('#insuranceDetails').hide(1000);
        }
    };

$(insProviderTable);

The issue is on page load the div insuranceDetails is appearing but if I change the value of paytype to Cash, nothing happens.

Please let me know where I am mistaken.

jsfiddle link https://jsfiddle.net/5bjfxdq4/


Solution

  • Just remove the inline onchange-handler and write:

    function insProviderTable() {
        if ($('#paytype').val() == 'Credit') {
            $('#insuranceDetails').show(1000);
        } else {
            $('#insuranceDetails').hide(1000);
        }
    };
    
    $(document).ready(function(){
        $('#paytype').on('change', function () {
            insProviderTable();
        });
    
        insProviderTable();      
    });
    

    Demo