How to enable multi-select dropdown on radio button select

Viewed 607

I have a multi select dropdown and two radio buttons. By default No should be checked and the drop down should be disabled. On change to Yes it should be enabled but it's not working. I'm not sure what I am doing wrong here.

This is my html:

<div class="form-group">
                        <label>Action Taken:</label>
                        <input type="radio" class="check" name="check" value="Yes">Yes
                        <input type="radio" class="check" name="check" value="No" checked>No
                        <select name="action[]" id="action" multiple class="action form-control" disabled>
                        <option value="Offcycle Salary Revision">Offcycle Salary Revision</option>
</select>

This is my javascript:

<script>
$('.check').change(function(){

   let select = $(this).parents('.form-group:first').find('select') ; 

   if( $(this).val() == 'Yes')
        select.attr('disabled' , false );
   else 
        select.attr('disabled' , true );

});
</script>

This is my javascript for multiselect:

$('#action').multiselect({
  nonSelectedText: 'Select Action',
  buttonWidth:'465px',
  maxHeight:450,
  includeSelectAllOption: true
 });

Can someone tell me what I am doing wrong here? It's working fine for a single select dropdown.

1 Answers

You need to target element which are dynamically created by mutliselect . So , you can target button which have mutliselect class then change attribute of that button.

Demo Code :

$(document).ready(function() {
  $('#action').multiselect({
    nonSelectedText: 'Select Action',
    buttonWidth: '465px',
    maxHeight: 450,
    includeSelectAllOption: true
  });


  $('.check').change(function() {
    //targetting mutliselect button
    $(this).closest(".form-group").find(".multiselect").attr('disabled', $(this).val() == 'Yes' ? false : true);
  });
  $('.check').trigger("change") //for triggering on page load..
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/js/bootstrap-multiselect.min.js"></script>

<div class="form-group">
  <label>Action Taken:</label>
  <input type="radio" class="check" name="check" value="Yes">Yes
  <input type="radio" class="check" name="check" value="No" checked>No
  <select name="action[]" id="action" multiple class="action form-control">
    <option value="Offcycle Salary Revision">Offcycle Salary Revision</option>
  </select>

Related