March 4, 2012
Select box opening input box jQuery
Question by user1235905
I am trying to open a have a select box show an input box when certain options are selected.
Here is my code:
$("document").ready(function() {
$('input.other').hide();
$('#amount').change(function() {
// var val = $(this).find('option:selected').text();
//alert(val);
var selectedValue = $(this).find(":selected").val();
//alert(selectedValue);
if( $(this).selectedValue == '25.00') {
// only if the radio button has a dob-field
$('input.other').show();// show only the following first
}
});
});
Answer by adeneo
You can target the selected option
inside the #amount
element directly by using the selector below, and find it’s value and compare it all inside the if statement.
The problem with the code in the question is $(this).selectedValue
, where $(this)
is referring to #amount
and not the option
, and selectedValue
is a variable, and should be used directly, but it’s not really necessary to use a variable here, as it’s fully readable and straight forward to do everything inside the if statement.
$('input.other').hide();
$('#amount').on('change', function(){
if( $(':selected', this).val() == '25.00') {
$('input.other').show();
}
});
Answer by Starx
Use selectedValue
to check not $(this).selectedValue
if( selectedValue == '25.00') { // only if the radio button has a dob-field
$('input.other').show();// show only the following first
}
Here is a full working snippet
$(document).ready(function() {
$('input.other').hide();
var selectedValue = $(this).find(":selected").val();
if( selectedValue == '25.00') {
// only if the radio button has a dob-field
$('input.other').show();// show only the following first
}
});
});