0

Jquery how to select dynamically created radio button. I have

<div id="rDataR">
</div>

MY JAVASCRIPT

 <script>
    $(function () {
    var items="<p>";

    for (var i = 0; i < length; i++) {

      items+="<input type='radio' id='myrdb' value='"+i+"'/>"

    }
    items+="</p>"
    $("#rDataR").html(items);

    }
    </script>

I try this, but not working

$('#myrdb').click(function () {
            if ($(this).is(':checked')) {
                alert($(this).val());
            }
        });
PgE92
  • 13
  • 1
  • 8

4 Answers4

1

try like following:

$(document).on('click','#myrdb',function () {
        if ($(this).is(':checked')) {
            alert($(this).val());
        }
    });
Ibrahim Khan
  • 19,912
  • 7
  • 35
  • 51
0

Instead of using duplicate id use class for user inputs then access them:

$(function(){
 $('.myrdb').filter(':checked').click(function(){alert('I am checked')})
});
M-Sha
  • 76
  • 1
  • 5
0

You need to change the dynamically added html to

items+="<input type='radio' class='myrdb' value='"+i+"'/>"

Since as per the convention dom id's must be unique.

And the jQuery event handler be like:

$(document).on('click','.myrdb',function () {
  if ($(this).is(':checked')) {
     alert($(this).val());
  }
});
jGupta
  • 2,175
  • 4
  • 21
  • 48
0

You logic is correct. You just missed some terminal colons here and there and had one small stray typo and you haven't defined your length. I also changed your radio elements to use class instead of id so they can be uniquely identified consistently. The changes are now as follows:

Your HTML:
<div id="rDataR"></div>

Your JavaScript
<script> $(function() { var items = "<p>"; var length = 10; //added length for (var i = 0; i < length; i++) { items += "<input type='radio' class='myrdb' value='" + i + "'/>"; } items += "</p>"; $("#rDataR").html(items); //corrected the typo #rDataE }); </script>

Your Trigger
$(".myrdb").click(function () { if ($(this).is(':checked')) { alert($(this).val()); } });

Let me know how it goes

Barilee
  • 57
  • 6