Albus One Albus One - 1 month ago 5
jQuery Question

jQuery repeat action on field change

I have jQuery function to uncheck radios (with id #radio_range_[any]) AND check radio (with id #an) when i start typing in text field (id #custom_range_duration)

$('#custom_range_duration').bind('keypress keyup blur', function() {
if ($('#custom_range_duration').val().length != 0){
$('input[id^="radio_range_"]').attr('checked', false);
$('#an').attr('checked', true);
}
});


When i load page and start typing in field, #radio_range_ unchecks, #and checks successfuly. However when i check #radio_range_ range again AND start typing in field - then #radio_range_ unchecks, but #an does not check again.

What am i doing wrong?

Answer

The reason it doesn't work the second time, is because jQuery checks the property, and you're changing the attribute, there's a difference.

You want to always use prop() when changing the checked state programatically

$('#custom_range_duration').bind('keypress keyup blur', function() {
    if ($('#custom_range_duration').val().length != 0) {
        $('input[id^="radio_range_"]').prop('checked', false);
        $('#an').prop('checked', true);
    }
});