简体   繁体   中英

How do you dynamically check a dynamically created checkbox in jQuery?

Been trying to find reference to exactly what I'm trying to do but not finding anything.

I have part of a form that is added with JS.

Once it has been added, I need to find a checkbox with a specific value and check it.

This works fine on anything that was there when the page loaded, but with dynamically-created elements I can't even manipulate them using JS in the console.

Here's the checkbox HTML:

<div class="check-container full optional-extra">
    <input id="Accomodation-Delegates[1]" type="checkbox" name="Delegates[1].SelectedOptionalExtras" value="43b595df-accc-e811-a2dd-00155d0fd300" data-price="25.00">
    <label for="Accomodation-Delegates[1]" class="check-label">Accomodation - £25.00</label>
</div>

Here's the section in the jQuery:

$('[value="43b595df-accc-e811-a2dd-00155d0fd300"]').prop('checked', true).trigger('change');

Please remember that this element doesn't exist on the page when it loads. I know how to dynamically check a checkbox normally.

You can have a set an function (setTimeout on DOMContentLoaded maybe) to trigger after some time after the DOM is initially loaded. This will be a jQuery selector that will look for your element on the page. After you select it, you can do whatever you need to do with it (checking the checkbox, changing background, etc.)

The point is though that you need the element rendered on the DOM at the point that your selector tries to select it (otherwise it will return empty)

You need to use event-delegation in order to bind events to dynamically created elements.

 $(document).on('click', '[type="checkbox"]', function() { console.log(this.value); }); // This is just to demonstrate the dynamic creating process. setTimeout(function() { $('#parent').append($('<div class="check-container full optional-extra"><input id="Accomodation-Delegates[1]" type="checkbox" name="Delegates[1].SelectedOptionalExtras" value="43b595df-accc-e811-a2dd-00155d0fd300" data-price="25.00"><label for="Accomodation-Delegates[1]" class="check-label">Accomodation - £25.00</label></div>')); }, 1000); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='parent'></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