简体   繁体   中英

How to display an element when the checkbox with certain value is checked?

There are three checkboxes and I want to show "text" below the form when "value C" is checked. When only the checkbox "Value C" is checked, it seems to work. But when I check multiple checkbox, for instance "Value A" and "Value C", "text" doesn't appear.

I'd like to show "text" whenever "Value C" is checked.

Note: I can't change HTML code, as it is created by WordPress plugin.

 $(function() { var $input = $('input[name="name123[data][]"]'); $input.change(function() { if ($('input[name="name123[data][]"]:checked').val() === 'value-c') { $('.text').show(); } else { $('.text').hide(); } }); });
 .text { display: none; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form action=""> <label><input type="checkbox" name="name123[data][]" value="value-a"><span class="mwform-checkbox-field-text">Value A</span></label> <label><input type="checkbox" name="name123[data][]" value="value-b"><span class="mwform-checkbox-field-text">Value B</span></label> <label><input type="checkbox" name="name123[data][]" value="value-c"><span class="mwform-checkbox-field-text">Value C</span></label> </form> <div class="text"> display this text in case "Value C" is checked </div>

You could stick the value on the selector to explicitly check that input. It's an ugly selector and could probably be done more efficiently, but it should work.

$('input[name="name123[data][]"]:checked[value="value-c"]').length

EDIT: Actually looking at your logic, you already have the inputs cached in a variable, so you could also do...

$input.filter('[value="value-c"]:checked').length

This would remove the extra DOM lookup.

You can select input using value attribute, like this:

 $(function() { $('input[name="name123[data][]"][value="value-c"]').change(function(e){ $('.text').toggle($(e.target).is(':checked')) }); });
 .text { display: none; }
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <form action=""> <label><input type="checkbox" name="name123[data][]" value="value-a"><span class="mwform-checkbox-field-text">Value A</span></label> <label><input type="checkbox" name="name123[data][]" value="value-b"><span class="mwform-checkbox-field-text">Value B</span></label> <label><input type="checkbox" name="name123[data][]" value="value-c" class="input--c"><span class="mwform-checkbox-field-text">Value C</span></label> </form> <div class="text"> display this text in case "Value C" is checked </div>

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