3
votes

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?

5
What's '3'? Don't you mean 'option3'? - tewathia

5 Answers

2
votes

Using a conditional operator (?:) is quite nice and easy:

demo

$("#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" : ""

1
votes

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('');
    }
});

FIDDLE

The value you specified(3) is not matching the value of any dropdown options.

0
votes

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!

0
votes

http://jsfiddle.net/FNaA9/

$("#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)

0
votes

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('');
    }
});