Reputation: 390
I have a select
with 2 options inside and my goal is to show/hide html elements depending on the option selected. There is no empty option, so there's always either "default" or "custom" selected.
For that I'm using jquery:
$(document).ready(function(){
$('.template-type').on('change', function() {
if ( this.value == 'default') {
$("#default_template").show();
$("#custom_template").hide();
} else {
$("#default_template").hide();
$("#custom_template").show();
}
});
});
But when I reload the page, regardless of the option saved, both html elements are visible again and a console log of this.options
tells me it's undefined
, but the option selected after reload matched the option saved before.
Only when I pick other option again it works as intended.
This is the select, a Symfony ChoiceType
field, just in case is needed:
case 'email_category':
$attrFields = array('class' => 'form-control template-type');
$formFieldType = ChoiceType::class;
$optionFields = array('choices' => array('Default' => 'default', 'Custom' => 'custom'), 'choices_as_values' => true, 'label' => 'Type of template used:');
break;
Upvotes: 1
Views: 398
Reputation: 171669
Assuming you are setting selected
server side , you can trigger the change event after you declare the change handler.
$(document).ready(function() {
$('.template-type').on('change', function() {
if (this.value == 'default') {
$("#default_template").show();
$("#custom_template").hide();
} else {
$("#default_template").hide();
$("#custom_template").show();
}
// trigger the change on page load
}).change();
});
Upvotes: 2