tonyshams
tonyshams

Reputation: 1

jQuery click() not working when switching radio set

I have a code that has a set of radio buttons. I change the buttons set based on given conditions. I need to know what radio button the user has selected once I switch the set. It works on the original set, but on the switched set click doesn't fire.

Here's a sample code. The original set of radio buttons work fine when checked and I get an alert of what the user selected. Added a button to switch the radios to another set, but when I check a button in the new (switched) set click doesn't fire.

I greatly appreciate your help and suggestions.

    <!DOCTYPE html>
<html>
<head>
    <script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {

            $("input[type='radio']").click(function() {
                var selected = $("input[type='radio'][name='opt']:checked");
                alert(selected.val());
            });

            $("#switchRadioSetButton" ).click(function() {
                var secondSetRadios = "<input type=\"radio\" name=\"opt\" value=\"B1\"/>B1<br/><input type=\"radio\" name=\"opt\" value=\"B2\"/>B2<br/>";
                $("#div1").html(secondSetRadios);
            });     

        });
    </script>
</head>
<body>
    <div id="div1" >
        <input type="radio" name="opt" value="A1"/>A1<br/>
        <input type="radio" name="opt" value="A2"/>A2<br/>
    </div>
    <button id="switchRadioSetButton">Switch Radio Set</button><br/>
</body>
</html>

Upvotes: 0

Views: 435

Answers (2)

ruthless
ruthless

Reputation: 309

so I think that the problem is like this one. Correct me if I'm wrong again. So basically the event is destroyed when you change the html of radio.


Answer From other question

This is most likely because the event is not delegated. When the page is loaded you bind the click events. But as the dom is manipulated (elements removed) the events are deleted. You would have to use a delegate for this.

Why does this jQuery .change event stop working after .click event


Code Removed

$("input[name='opt']").click(function(){
    var selected = $("input[type='radio'][name='opt']:checked");
    alert(selected.val());
});

Code I Added

$('#div1').on('change', ':radio', function(){
    var selected = $("input[type='radio'][name='opt']:checked");
    alert(selected.val());
});

Example

https://jsfiddle.net/c37at0jn/

Upvotes: 2

areeb
areeb

Reputation: 422

use prop()

 $("input[type='radio']").prop(function(){
   //code goes here
 });

instead of click()

Upvotes: 0

Related Questions