Reputation: 105
I want to make a function that:
If the user selects the specific option in the select dropdown list, some text will be added to the textarea.
If the user selects other option in select, the textarea will be cleared.
I have tried this:
HTML
<select name="Problem" id="Problem">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
<textarea name="csContent" id="csContent">
jQuery
$("#Problem").on("change", function () {
if ($('#Problem').val() == '3') {
$('#csContent').html('blahblahblah');
} else {
$('#csContent').val('');
}
});
However this doesn't work. Is there anything I missed?
Upvotes: 3
Views: 3595
Reputation: 66663
The value check is incorrect. It should be checked against option3
instead of just 3
$("#Problem").on("change", function () {
if ($(this).val() == 'option3') {
$('#csContent').html('blahblahblah');
} else {
$('#csContent').val('');
}
});
Upvotes: 0
Reputation: 206078
Using a conditional operator (?:) is quite nice and easy:
$("#Problem").on("change", function () {
$('#csContent').html( this.value.match("n3") ? "blahblahblah" : "" );
});
Note: .match("n3") (searching for occurence "n3" in your value) method might also match option32
. If you need to be more specific than use:
this.value === "option3" ? "blahblahblah" : ""
Upvotes: 2
Reputation: 115222
It's working fine , change the value 3
to option3
.
<select name="Problem" id="Problem">
<option value="option1">option1</option>
<option value="option2">option2</option>
<option value="option3">option3</option>
<option value="option4">option4</option>
</select>
<textarea name="csContent" id="csContent"></textarea>
$("#Problem").on("change", function () {
if ($(this).val() == 'option3') {
$('#csContent').val('blahblahblah');
} else {
$('#csContent').val('');
}
});
The value you specified(3
) is not matching the value of any dropdown options.
Upvotes: 1
Reputation: 24825
$("#Problem").on("change", function () {
if ($(this).val() == 'option3') {
$('#csContent').html('blahblahblah');
} else {
$('#csContent').html('');
}
});
Notice .val in the else statement has changed to .html
This is also important as otherwise you can only change the item once (try changing to option 3 - then option 1 then option 3 again on other answers - it won't update the text box the second time)
Upvotes: 0
Reputation: 15860
It won't work, since you're using wrong value
$('#problem').val() == '3'
will never b e true since there is no such value.
Use this:
if ($('#Problem').val() == 'option3') {
$('#csContent').html('blahblahblah');
} else {
$('#csContent').val('');
}
The issue was only 3
replace it with option3
and you're good to go!
Upvotes: 0