Why clicking on the male radio button does not work?
<div id="m_wrapper">
<input id="m" type="radio" name="sex" value="male" />Male<br>
</div>
<input id="f" type="radio" name="sex" value="female" />Female
<input id="o" type="radio" name="sex" value="other" />Other
$("#m_wrapper").click(function(e){
$("#m").prop('checked', true);
return false;
});
I know that here -> return false is equivalent to call e.preventDefault() AND e.stopPropagation()
However, when I click on the radio button, I have an explicit line setting the property checked to true for the Male radio button. Why will preventDefault()
will UNDO
something I set?
By the way, clicking anywhere inside 'm_wrapper'
checks the radio button. Which makes sense.
I know that removing return false
will fix the issue. The question is 'why?'
$("#m_wrapper").click(function(e){
$("#m").prop('checked', true);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="m_wrapper">
<input id="m" type="radio" name="sex" value="male" />Male<br>
</div>
<input id="f" type="radio" name="sex" value="female" />Female
<input id="o" type="radio" name="sex" value="other" />Other
This is what happens when you click "Male" input button.
Click event on the input makes it checked. Better to say, attempts to make it checked. To actually commit this new state and render it, event must finish its lifecycle without being prevented. However..
Event bubbles up the DOM tree and reaches parent div element which has click handler attached to it. This event handler prevents default behaviour, which in case of radio button (and checkbox) is toggling checked state. Calling e.preventDefault()
is the same as return false
in this case.
return false
instruction dictates that radio input remained unchecked because according to its initial state after click it should have become checked (if default was not prevented). So return false
forces radio to remain unchecked even though previous line $("#m").prop('checked', true);
got it checked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With