简体   繁体   中英

jquery not working with dynamically added elements

In my HTML body I have this code:

 $.post('/GetManufacturers',(Data)=> { Data.Manufacturers.forEach(i => { $('#Manufacturers').append(`<input type="radio" name="Manufacturers" id="MF" value="${i}"> <label>${i}</label><br>`); }); }); $('input[name="Manufacturers"]').change(()=>{ console.log($("input[type='radio'][name='Manufacturers']:checked").val()); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <label>Manufacturers:</label> <div id="Manufacturers"></div>

It adds the radio buttons in perfectly and they work fine, but when I select a radio button the .change() doesn't respond at all. I placed it inside and outside the document ready either or doesn't work.

Because they are dynamically added, your selectors won't pick them up since your selcetors have essentialy already queried the dom.

You'd have to change

 $('input[name="Manufacturers"]').change(()=>{        
    console.log($("input[type='radio'][name='Manufacturers']:checked").val());       
 })

to

 $('body').on('change', 'input[name="Manufacturers"]', () => {        
    console.log($("input[type='radio'][name='Manufacturers']:checked").val();       
 })

This is the case where you should use Event Delegation in JQuery.

Elements are added after the content is loaded.

And in the beginning you're trying to bind an event to a selector which doesn't have any element in the page.

 const mockUrl = 'https://run.mocky.io/v3/48c668b0-291c-4704-b5ed-c14f5038b2c9' $(() => { $.post(mockUrl, (Data) => { Data.Manufacturers.forEach(i => { $('#Manufacturers').append(`<input type="radio" id="${i}" name="Manufacturers" id="MF" value="${i}"> <label for="${i}">${i}</label><br>`) }); }) }) $("body").on("change",'input[name="Manufacturers"]',() => { console.log($("input[type='radio'][name='Manufacturers']:checked").val()); })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <body> <label>Manufacturers:</label> <div id="Manufacturers"></div> </body>

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