简体   繁体   中英

jQuery returning incorrect value of checked radio button when using styled buttons

I'm using the jQuery plugin ScrewDefaultButtons to style my radio buttons, but it seems it comes with a side effect that it doesn't return the correct value when getting it via jQuery. I am running a function when they are clicked and I am trying to get the value of the radio button the user selected, but it seems to returns the value of the previously selected radio button instead of the one that was just selected.

If I remove the class pretty_rb , which disables the styling then it works fine.

I am trying to get the value with:

jQuery('input[name=tax_account_type]:checked').val();

My HTML:

<input type="radio" name="tax_account_type" id="individual" class="pretty_rb" value="0" onclick="updateRegForm();" checked required>
<input type="radio" name="tax_account_type" id="business" class="pretty_rb" value="1" onclick="updateRegForm();" required>

Edit: Fiddle: http://jsfiddle.net/94UtB/2/

The problem is that ScrewDefaultButtons wraps the input elements in a div and then hides the input element.
This div has a click event that checks the correct hidden input element.
However. Since you have an onClick event YOUR event is run before the change.
That is why you get the old value.

To solve this add the following code after the call to screwDefaultButtons :

$('.styledRadio').on('click', updateRegForm);

or

$('.pretty_rb').on('click', updateRegForm);

Remember to remove the onlick attribute from the HTML.

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