简体   繁体   中英

jQuery - On Selection option change, show/hide DIV

Based on the chosen option in a select list, I want to show one of the following DIVs:

<div id="field-person">Blah</div>

<div id="field-company">Blah 2</div>

This is the select and jQuery I have right now, which when the A person option is selected, should show #field-person , otherwise it should remain hidden:

<select name="sub_type" id="sub_type">
  <option value="company">A company</option>
  <option value="person">A person</option>
</select>

$(document).ready(function() {
  var f = $("#field-person");
  $("#sub_type").change(function() {
    if (this.checked && this.value == "person") {
      f.show();
    } else {
      f.hide();
    }
  }).change()
});

Yet when I select the person option, nothing happens, same goes for selecting the company option. No change, and nothing in the Chrome Console. Been pulling my hair out on this one for about an hour now, any help would be appreciated, jQuery isn't my strong suit!

Here's a link to the actual code that I'm using: JSFiddle

Change your if-statement to:

if (this.value == "person") {
   ...
}

The select element doesn't have a .checked property. So this.checked returns undefined , which will make the condition false.

Demo

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