Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery event propagation (return false)

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
like image 595
Cacho Santa Avatar asked May 28 '15 21:05

Cacho Santa


1 Answers

This is what happens when you click "Male" input button.

  1. 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..

  2. 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.

  3. 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.

like image 96
dfsq Avatar answered Oct 04 '22 23:10

dfsq