Reputation: 2926
I have a drop down select box and input text box. Select box display my categories and its look like this:
<select id="category" name="category">
<option value="">Please select...</option>
<option value="1">Category-1</option>
<option value="2">Category-2</option>
<option value="3">Category-3</option>
<option value="4">Other</option>
</select>
Input text box is like this:
<input type="text" id="otherCategory" name="otherCategory" value="" style="display: none;">
My question is. when an user select only "Other" from dropdown then I need to populate the input text.
I tried it something like this:
$(document).ready(function() {
$('#category').change(function() {
var myValue = $(this).val();
var myText = $("#category :selected").text();
if (myText != '' AND myText == "Other") {
$("#otherCategory").show();
}
});
});
But I couldn't get it to work. Can anybody tell how I figure this out.
NOTE: my dropdown select populating dynamically.
Thank you.
Upvotes: 3
Views: 13391
Reputation: 2480
Try this Demo, if user selects other option showing input field else hiding.
$(document).ready(function() {
$('#category').change(function() {
var myValue = $(this).val();
var myText = $("#category :selected").text();
if (myText == "Other") {
$("#otherCategory").show();
}
else{
$("#otherCategory").hide();
}
});
});
Upvotes: 2
Reputation: 87203
You are missing &&
in if
condition. Also, your condition
myText != ''
is redundant and not required.
And you need to hide the input
when selection changed.
$(document).ready(function () {
$('#category').on('change', function () {
var myValue = $(this).val();
var myText = $.trim($("#category :selected").text()).toLowerCase(); // Trim spaces and convert to lowercase for comparison
$("#otherCategory").toggle(myText === 'other');
});
});
Demo: https://jsfiddle.net/tusharj/8ykfmtyt/1/
Upvotes: 6
Reputation: 148110
You need to use &&
instead of AND
if (myText != '' && myText === "Other") {
$("#otherCategory").show();
}
You can further optimize it by hiding with option other then 'other' is selcted. You do not need to check if it is not empty when you are comparing it with string 'other' so I removed that condition from if statement.
$('#category').change(function () {
$(this).find(":selected").text() === "Other" ?
$("#otherCategory").show() : $("#otherCategory").hide();
});
Upvotes: 4