Populating textbox input based on select dropdown in JQuery
I have a dropdown select box and an input text box. Select the box that displays my categories and it looks 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>
The input text box looks like this:
<input type="text" id="otherCategory" name="otherCategory" value="" style="display: none;">
My question. when the user only selects "Other" from the dropdown, I need to fill in the input text.
I tried 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 anyone tell me how I understand this.
NOTE: my dropdown is picking dynamically.
Thank.
You are missing &&
c if
. Also, your condition
myText != ''
is redundant and unnecessary.
And you need to hide input
when the choice has 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/
You need to use &&
insteadAND
Live Demo
if (myText != '' && myText === "Other") {
$("#otherCategory").show();
}
You can optimize it even further by hiding with the other option, then "other" will be highlighted. You don't need to check if it is empty when you compare it to the string 'other', so I removed that condition from the if statement.
Live Demo
$('#category').change(function () {
$(this).find(":selected").text() === "Other" ?
$("#otherCategory").show() : $("#otherCategory").hide();
});
Try Demo if user chooses another option which hides the input field.
$(document).ready(function() {
$('#category').change(function() {
var myValue = $(this).val();
var myText = $("#category :selected").text();
if (myText == "Other") {
$("#otherCategory").show();
}
else{
$("#otherCategory").hide();
}
});
});