Reputation: 67
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.
Upvotes: 1
Views: 1940
Reputation: 1497
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();
})
Upvotes: 3
Reputation: 96
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>
Upvotes: 1