Chris Pilie
Chris Pilie

Reputation: 451

jQuery on change and on load solution

I am trying to stream-line some code that I believe is a little sloppy. Basically a script that checks to see the value of a select box and shows or hides a div based on the value selected. I want to check the value on load as well as on change. Is there a cleaner way to do this?

// Required items  
 $(document).ready(function(){  
 if($("#credentials").attr("selectedIndex") == "None") {
    $('#CDiv').show();
 }else{
     $('#CDiv').hide();
   }
 $("#credentials").change(function(){
    if ($(this).val() == "None" ) {
        $('#CDiv').show();     
    } else {
        $('#CDiv').hide();      
        }  
    });    
});

I appreciate any help with this. I am still a little green on jQuery. Thanks!

Upvotes: 0

Views: 111

Answers (1)

Ram
Ram

Reputation: 144659

selectedIndex is a property not an attribute and it doesn't return "None". If you want to read it's value you should use prop method instead. That being said you can trigger the change event instead of using if statement. By triggering the event your change handler is executed once on DOM ready:

$("#credentials").on('change', function() {
    $('#CDiv').toggle( this.value === 'None' ); 
}).change();

Upvotes: 3

Related Questions