Search code examples
jqueryradio-buttonjquery-eventsprop

Handler for checking radio button based on another input field stops working after unchecking radio button from another handler


I have a form with a radio button and a text input field:

<input type="radio" name="foo" value="bar">
<input id="baz" type="text">
...

The text input field has a keyup handler associated with it that will check the radio button when I start typing in the text input field:

$('#baz').on('keyup', function() {
  var bar = $('input[name="foo"][value="bar"]');
  if (!bar.is(':checked')) {
    bar.prop('checked', true);
  }
});

The form also has a "Reset" button (with an id of reset) and the following click handler:

$('#reset').on('click', function() {
  $('input[type="radio"]').prop('checked', false);
  $('input').val('');
});

The problem: The keyup handler for the input field stops working after clicking the "Reset" button.

When I augment the handler with calls to console.log like this:

$('#baz').on('keyup', function() {
  var bar = $('input[name="foo"][value="bar"]');
  if (!bar.is(':checked')) {
    console.log('not checked');
    bar.prop('checked', true);
    console.log('New value for "checked" property: ' + bar.prop('checked'));
  } else {
    console.log('checked');
  }
});

I get the following output when I enter two characters before clicking the "Reset" button:

not checked

New value for "checked" property: true"

checked

When entering two characters after clicking the "Reset" button, the output looks like this:

not checked

New value for "checked" property: undefined

not checked

New value for "checked" property: undefined

The checked property of the radio button is now undefined instead of false. (I am assuming that that is the reason why the keyup handler can't set it anymore?)

I'd like to understand what's going on here. How do I need to modify my code to keep the functionality of the keyup handler after clicking "Reset"?

I feel like I'm missing something obvious, but so far I haven't been able to dig up a solution for this problem on here or elsewhere.


Solution

  • In your #reset event handler you're setting the value of all input elements to ''.

    In your keyup handler you're selecting the radio button using its name and value:

    var bar = $('input[name="foo"][value="bar"]');
    

    Which selects nothing, because you no longer have input[value="bar"]