简体   繁体   中英

Select div if checkbox checked

How can I select the "container" div if the input checkbox inside "myCheck" is checked?
I am using the jquery print area plugin, so basically if checkbox is checked, I need to select the container div so the code should look something like $(".myCheck input:checked > div").printArea();

Here is my HTML:

<div class="content">
        <div class = "myCheck"><input type="checkbox" />
            <div class = "container"> 
                <img src="https://www.kent.ac.uk/graduateschool/images/email-thumbnail.jpg" alt="My new Image">
            </div>
            </div>
        </div>

I have tried using the > selector but it does not seem to work:

alert( $(".myCheck input:checked > div").printArea()

Also tried this:

alert( $(".myCheck input:checked").children()).printArea()

You could use .next()

 $('input').on('change', function(){ console.log($(".myCheck input:checked").next().html()); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="content"> <div class = "myCheck"><input type="checkbox" /> <div class = "container"> <img src="//placehold.it/50" alt="My new Image"> </div> </div> </div> 

Using jQuery you can use this for the checked value:

$('.myCheck').prop('checked', true);

And you can probably use a callback function to select the container :

$('.myCheckbox').is(':checked', function(e){
  e.preventDefault(e);
  $('container').theMethodYouWantToUse
});

Hope it help you

Run the example below, check and uncheck the component, hope it helps!

Basically, I'm using simple callback for checkbox's clicks, controlling it's state, and selecting the content if the component is checked.

 // Waiting for DOM load $(document).ready(function() { // Callback for checkbox's click $(".myCheck > input[type='checkbox']").on("click", function() { // Setting the container variable as null var container = null; // Checking if the checkbox is "checked" if ($(this).is(":checked")) { // Selecting the container node object, so you can use it as you want var container = $(".container"); // Console warnings console.info("Container selected, the checkbox must be checked!"); console.log("Some test information from container: " + $(container).find('span').html()); } else { // Console warnings console.info("Container not selected, the checkbox must be checked!"); } }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="content"> <div class="myCheck"> <input type="checkbox" /> <div class = "container"> <span>Some example content..</span> </div> </div> </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