Radio button inside anchor element is reset after jQuery click handler

Posted by GrievousAngel on Stack Overflow See other posts from Stack Overflow or by GrievousAngel
Published on 2011-01-06T11:25:16Z Indexed on 2011/01/06 15:54 UTC
Read the original article Hit count: 260

Filed under:
|
|
|

I have a situation where an element, of type radio, is contained in an element. The anchor element has a href but I want to override that behaviour by adding a jQuery 'click' handler to the element.

The click handler makes the radio button inside it the selected one within the group. This all works when the anchor is clicked, however, when the radio button is clicked it appears that jQuery resets the selected radio to the previously selected one!

Here is a the simplified page that duplicates the issue:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $("#a1").click(function(event) {
                anchorClicked("a1");
                return false;
            });
            $("#a2").click(function(event) {
                anchorClicked("a2");
                return false;
            });
        });

        function anchorClicked(anchorId)  {
            $('#' + anchorId + ' input:radio').attr("checked", true);
            alert("Look at what is selected and what happens after the event when this dialog is closed!");
        }
    </script>
</head>
<body>
    <form>
        <ul>
            <li id="li1"> 
                <a id="a1" href="javascript:alert('default functionality')">
                    <input value="1" name="rb" type="radio" id="rb1">
                    <span>Details 1</span>
                </a>
             </li>
            <li id="li2"> 
                <a id="a2" href="javascript:alert('default functionality')">
                    <input value="2" name="rb" type="radio" id="rb2">
                    <span>Details 2</span>
                </a>
             </li>
        </ul>
    </form>
</body>

Does anyone have any idea how I can prevent jQuery for resetting the radio button?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery