abbas
abbas

Reputation: 228

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/

Upvotes: 0

Views: 1854

Answers (3)

empiric
empiric

Reputation: 7878

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

Upvotes: 0

Dhaval Marthak
Dhaval Marthak

Reputation: 17366

You can try like this:

You can trigger change() on load like following:

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

Demo

Upvotes: 1

Toby Cannon
Toby Cannon

Reputation: 735

Simply add this to the bottom of your existing script

$("#paytype").bind('change', function(){
$(insProviderTable);    

});

Add between main body and

$(insProviderTable);

Hope this helps, let me know how you get on!

Upvotes: 0

Related Questions