简体   繁体   中英

How can I use jQuery change() with checkboxes?

I'm working with Sharepoint and am creating a list with injected Javascript and JQuery. I'm trying to show a text box if the user selects the "Other" option. This option originally came from a dropdown but is now based on checkboxes for multiple selections.

Here's the code based on the dropdown:

function TargetAudienceChange(){
  $('select').on('change', function(){
    var TargetAudience = $('select[id*=TargetAudience]').val();
    if (TargetAudience == 'Other (Specify)'){
      $("h3.ms-standardheader:contains('Other Cultural Awareness')").closest("tr").show();
    }
    else {
      $("h3.ms-standardheader:contains('Other Cultural Awareness')").closest("tr").hide();
      $('input[id*=OtherTargetAudience]').val("");
    }
  })
}

I tried this without success:

function TargetAudienceChange(){
  $('checked').on('change', function(){
    var TargetAudience = $('checked[id*=TargetAudience]').val();
    if (TargetAudience == 'Other (Specify)'){
      ...
    }
    else {
      ...
    }
  })
}

How can I make this code work for options based on checkboxes that allow multiple selections?

This selector:

$('checked')

Is looking for elements like this:

<checked />

That's not what a checkbox is. Take a look at your HTML. A checkbox is this:

<input type="checkbox" />

So you'd use something like this:

$('input[type="checkbox"]')

or the shorter:

$('input:checkbox')

Same with your other selector:

$('checked[id*=TargetAudience]')

There's no <checked /> element, you'd look for elements like:

$('input[id*=TargetAudience]')

or perhaps:

$('input[type=checkbox][id*=TargetAudience]')

Note: If this selector is targeting more than one element, then .val() is probably only going to return the value of the first matched element. How you'd address that depends on whether you want to target a more specific element or if what you actually want is a collection of values from multiple elements.

I was able to solve this with:

function TargetAudienceChange(){
  $('input[id*=TargetAudience]').on('change', function(){
    if ($(this).prop('checked') == true && $(this).next().text() == 'Other (Specify)'){
      $("h3.ms-standardheader:contains('Other Cultural Awareness')").closest("tr").show();
    }
    else if ($(this).prop('checked') == false && $(this).next().text() == 'Other (Specify)') {
      $("h3.ms-standardheader:contains('Other Cultural Awareness')").closest("tr").hide();
      $('input[id*=OtherTargetAudience]').val("");
    }
  })
}

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