Reputation: 107
I want to reveal a link when a certain dropdown option is selected in a html5 form.
On page load I want to remove the link with id "pension-faq-icon" and only display it if the user selects <option value="<%= User::LENDER_TYPE_PENSION_INDIVIDUAL %>" id="select-ind-pension">Individual Pension Account</option>
Html:
<div class="seven columns">
<div class="select-holder icon icon_select">
<select name="user[user_subtype]" id="user_lender_type">
<option value="">Select type</option>
<option value="<%= User::LENDER_TYPE_INDIVIDUAL %>" id="select-ind">Individual Lender</option>
<option value="<%= User::LENDER_TYPE_PENSION_INDIVIDUAL %>" id="select-ind-pension">Individual Pension Account</option>
<!--<option value="sme" id="select-sme">Investment Business</option>-->
</select>
</div>
<p class="icon icon_info form-help-pension-faq show" id="pension-faq-icon">Need help? <a href="<%= faq_pension_path %>" target="_blank">Read Our Pensions FAQ</a></p>
</div>
js file:
var user_type = $("#user_user_type").val();
var option_type = $("#select").val();
if(user_type == 'lender') {
$('#pension-faq-icon').addClass('display-none');
}
if (option_type == 'individual_pension_lender'){
//$('#pension-faq-icon').removeClass('display-none');
console.log(option_type);
}
Right now the code above is successfully not displaying the line with the id "pension-faq-icon". How can I add it again if the user selects the specific dropdown option mentioned above?
Upvotes: 1
Views: 49
Reputation: 337637
To make this work you need to attach a change
event handler to the select
which runs whenever the user selects an option. At the moment your logic only executes when the page loads.
Also note that you can simplify the process by providing a boolean to toggle()
which specifies whether to hide or show the relevant element. Try this:
$('#user_lender_type').change(function() {
$('#pension-faq-icon').toggle($(this).val() == 'individual_pension_lender');
});
#pension-faq-icon {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="seven columns">
<div class="select-holder icon icon_select">
<select name="user[user_subtype]" id="user_lender_type">
<option value="">Select type</option>
<option value="lender" id="select-ind">Individual Lender</option>
<option value="individual_pension_lender" id="select-ind-pension">Individual Pension Account</option>
</select>
</div>
<p class="icon icon_info form-help-pension-faq show" id="pension-faq-icon">
Need help?
<a href="<%= faq_pension_path %>" target="_blank">Read Our Pensions FAQ</a>
</p>
</div>
Upvotes: 1