简体   繁体   中英

Get the value of a dynamically added radio button (JQuery)

I'm trying to get the value of the dynamically generated radio button when this button is selected.

Here is my code snippet:

<div id="divContainer">
</div>

Jquery:

$("#divContainer").on("change", $('input[name="name1"]:checked'), function () {
            var selectedVal=$('input[name="name1"]:checked').val();
            console.log(selectedVal);
    });

The value of the selectedVal is returning null here.


Resolution:

The default value was not properly assigned. I updated my code snippet which generates the radio button:

('#radiBtn').attr("value",val);

This resolved the issue.

Remove the $ wrapping from selector just use 'input[name="name1"]:checked' t for getting changed object use this

 var div = $("#divContainer").on("change", 'input[name="name1"]:checked', function() { var selectedVal = $(this).val(); console.log(selectedVal); }); $('<input>', { name: 'name1', type: 'radio', value: 1 }).appendTo(div); $('<input>', { name: 'name1', type: 'radio', value: 2 }).appendTo(div); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="divContainer"> </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