Andrew Algard
Andrew Algard

Reputation: 105

jQuery radio button on change function runs twice

I have this little function in my website:

$( 'form .radio_buttons' ).change( doTheFunction )

which works fine, but I noticed that it is always running twice whenever a radio button option changes. After thinking for 5 seconds I realized what was going on; there are 2 change events occurring:

change 1: the checked radio button is unchecked 
change 2: the unchecked radio button is checked

My question is how do I treat this as one event? is there a slick Javascript function I can use?

EDIT:
It seems there may be a deeper issue going on here, I can't duplicate the problem outside of my app, but Scott Marcus' answer worked for me. I'll have to figure out why change events are firing twice...

Upvotes: 0

Views: 1700

Answers (2)

Scott Marcus
Scott Marcus

Reputation: 65806

This really shouldn't be happening and without your code we really can't say for sure what the issue is, but rather than working with the change event, you can use the click event.

It may be that there is other code in your application that causes your change callback to be firing twice.

Upvotes: 1

mscdeveloper
mscdeveloper

Reputation: 2889

$('[name=myradio]').change(function(){
	 if($(this).is(':checked')){
	 	 alert('checked : '+ $(this).val());
	 }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>



<label><input type="radio" name="myradio" value="radio1">radio 1</label>
<label><input type="radio" name="myradio" value="radio2">radio 2</label>

Upvotes: 1

Related Questions