简体   繁体   中英

Show div that is selected in dropdown and hide other divs using javasccript

Right now I have a javascript block in my webpage that will show the div that the user has selected from a dropdown, and hide the others that aren't currently selected. It currently works, but is throwing an error in my chrome developer console. I would like to clean this up to make sure it isn't throwing an error.

the error

Uncaught TypeError: Cannot read property 'toLowerCase' of null
**javascript**

JS

$(function() {
   $('#loan_application_requested_purpose').on("change",function(){
     $(".loan_purpose").hide();
     // change all spaces to underscore and grab the first part of Expansion/
     var $div = $("#"+$(this).val().toLowerCase().replace(/ /g,"_").split("/")[0]);
     if ($div.length>0) $div.show();
     else $("#other").show(); 
     }).change(); // run change on load to show relevant already selected
});

html

<select id="loan_application_requested_purpose" name="loan_application[requested_purpose]" class="valid">
    <option disabled="disabled" selected="selected" value=""></option>
    <option value="Contract Bid">Contract Bid</option>
    <option value="Equipment Purchase">Equipment Purchase</option>
    <option value="Hiring Employees">Hiring Employees</option>
    <option value="Inventory Purchase">Inventory Purchase</option>
    <option value="Marketing">Marketing</option>
    <option value="Refinancing">Refinancing</option>
    <option value="Expansion/Renovation">Expansion/Renovation</option>
    <option value="Working Capital">Working Capital</option>
    <option value="Other">Other</option>
</select>

Please read the error message carefully:

Uncaught TypeError: Cannot read property 'toLowerCase' of null

This clearly indicates the result of $(this).val() is null in some instances.

The jQuery documentation describes the single case in which this could occur:

In the case of select elements, it returns null when no option is selected

This includes the option with the empty value you have listed. Perhaps you should try retrieving the value first, then checking for null before you perform the other operations.

The problem is the disabled first value. It returns null because it cannot be selected.

Change it to either not be disabled or change your script to

$(function() {
   $('#loan_application_requested_purpose').on("change",function(){
     $(".loan_purpose").hide();
     // change all spaces to underscore and grab the first part of Expansion/
     var val = $(this).val();
     var $div = val?$("#"+val.toLowerCase().replace(/ /g,"_").split("/")[0]):$("#other");
     if ($div.length) $div.show(); 
   }).change(); // run change on load to show relevant already selected
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM