John Davidson

javascript - Select2 Disable other Select2 based on option

0 comments
Message:


I have two select2 options



I want to implement something like, if user click daily they can use the Select2 option of Days, But if they select Monthly then the another Select2 button will be disable. Can u check why my code isn't working.


{{ Form::select('type', $type, null, ['class' => 'form-control select2', 'onchange' => 'myFunction()', 'id' => 'recurring_type', 'required' => 'true', }}

{{ Form::select('days', $days, null, ['class' => 'form-control select2', 'id' => 'days', 'required' => 'true', }}

And this is the javascript


function myFunction() {
if($(this).val() === 'Daily') {
$('#days').select2('disable');
} else {
$('#days').select2('disable');
}
}


My Answer:
You can achieve this functionality using jQuery. Here's an example code snippet that demonstrates how to disable the second Select2 based on the value selected in the first Select2:

javascript
$(document).ready(function() {
$('#type').select2(); // Initialize the first Select2

$('#frequency').select2(); // Initialize the second Select2

$('#type').on('change', function() {
var selectedValue = $(this).val();

if(selectedValue === 'daily') {
$('#frequency').prop('disabled', false).select2('enable');
} else if(selectedValue === 'monthly') {
$('#frequency').prop('disabled', true).select2('disable');
}
});
});


In this code snippet:
- `#type` refers to the first Select2 element that allows the user to select either "daily" or "monthly".
- `#frequency` refers to the second Select2 element that will be disabled/enabled based on the selection in the first Select2.
- We use the `on('change')` event handler to detect when the value in the first Select2 changes.
- Depending on the selected value, we either enable or disable the second Select2 using the `prop('disabled', true/false)` method.
- We also use the `select2('enable')` and `select2('disable')` methods to enable or disable the Select2 dropdown.

Make sure to replace `#type` and `#frequency` with the actual IDs of your Select2 elements in your HTML code.

Rate this post

4 of 5 based on 9824 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us