Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Can't "catch" an element

I have an input:checkbox element on my project and I want to do this: /Toggle input true or false*/ $("#toggleinp").on("change", () => { if ($(this).is(':checked')) { $(this).attr('value', 'true'); } else { $(this).attr('value', 'false'); } })

but when I'm checking on the debugger, it automatically entering this once refreshing the page. Also, nothing happened when I'm checking the box. The input field automatically created by an ajax that upload the main home page:

$("#coinsDiv").append(<div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">${resualt[i].name} - ${resualt[i].symbol}</h5> <label class="switch"> <input type="checkbox" id="toggleinp"> <span class="slider round"></span> <button href="#" class="btn btn-primary collapsible ${resualt[i].id}" data-toggle="collapse">More Info</button> <div class="content"> <p class="${resualt[i].id}"></p> </div> </div> </div>);

1 Answer

Steven Parker
Steven Parker
243,266 Points

When you say "The input field automatically created by an ajax", I assume you mean that the field is created after the JavaScript runs. If so, the event listener would not have been attached to the checkbox since the ID ("#toggleinp") was not present in the document at that time.

To make the handler work you would either need to set it up after the element was fully loaded, or you could establish a delegated handler on an element that already exists and will be a parent of the loaded control.