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?
The easiest way I've found to solve this issue is to remove the href attribute from the anchor element during the click event:
$("#a1").click(function(event) {
this.removeAttribute("href");
anchorClicked("a1");
});
This means I no longer need to return false to prevent the default behaviour and the event can bubble up the DOM safely and everything then works.