Kevin Kevin - 7 months ago 22
Javascript Question

check checkbox based on dropdown

I was wondering if there is a way to auto check certain boxes based on the value from a dropdown selection. I have been searching forever and I can only seem to find ways to SHOW OR HIDE checkboxes based on dropdown but that is not what I am looking for.

Answer

You can do this pretty easily with jQuery. This code listens for a change event from a dropdown with id="dropdown" and checks the checkbox with id="checkbox" if the dropdown text was equal to 'foo'.

$("#dropdown").change(function() {
  if($('#dropdown :selected').text() === 'foo') $('#checkbox').prop('checked', true);
});

If you want to uncheck the box when the selection is changed again something like this might be better:

$("#dropdown").change(function() {
  var text = $('#dropdown :selected').text();
  $('#checkbox').prop('checked', text === 'foo');
});

Fiddle

Comments