简体   繁体   中英

jQuery Mobile click event.preventDefault does not seem to prevent change

I am trying to prevent a radio button from changing when a use clicks, it works when using standard jQuery but when you include jQuery Mobile it does not seem to work, is there something else I have to do in jQuery Mobile?

<fieldset data-role="controlgroup"  data-type="horizontal">
        <input type="radio" name="trade-direction" id="buy" value="B" checked="checked" />
        <label for="buy">Buy</label>

        <input type="radio" name="trade-direction" id="hold" value="H"  />
        <label for="hold">Hold</label>

        <input type="radio" name="trade-direction" id="sell" value="S"  />
        <label for="sell">Sell</label>
</fieldset>

$('[name="trade-direction"]:radio').click(function(event) {
    if(!confirm("Do You Want To Change?")) {
        event.preventDefault();
    }
});

below is a link to the code in jsFiddle.

http://jsfiddle.net/mikeu/xJaaa/

The problem is that with jQuery.Mobile, the element that is effected by the UI change is not the input element. In fact, the radio element isn't actually clicked at all. The Element that is clicked is <div class="ui-radio"> . If you want to bind to the radio input itself, you need to use the change event, but in this case it won't work for you, because the function gets called after the change has already taken place.

What you need is something like this:

// Probably a good idea to give your fieldset an ID or class

 $('fieldset').delegate('.ui-radio','click',function(event){
      if(!confirm("Do You Want To Change?")) {
        event.stopImmediatePropagation();
        event.preventDefault();
      } 
  })

The event.stopImmediatePropagation() prevents the the .ui-radio from triggering the click event to the input, and the event.preventDefault prevents the default action. The stopImmediatePropagation may not be necessary, but it gives an added guarantee that may be helpful across different browsers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM