If I have a listbox and a textarea:
<textarea id="MyTextArea"></textarea>
<select id="SelectList" multiple>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
What I would like to do is... if there are more than 0
selected options.. then append the text There are selections
to the textarea.
If the user deselects the options to the point where there are 0
selected options then erase that string from the textarea, but keep whatever else the user typed in that textarea.
Here is what I have:
$("#SelectList").change(function(){
var count = $("#SelectList> option:selected").length;
var string = "There are selections.";
var txtVal = $("#MyTextArea").val();
if (count > 0 && txtVal.indexOf(string) == -1) {
$("#MyTextArea").append(string);
}
else if (count > 0 && txtVal.indexOf(string) != -1) {
}
else if (count === 0 && txtVal.indexOf(string) != -1) {
var indexOfString = $("#MyTextArea").value.indexOf(string);
$("#MyTextArea").value.substring(0, indexOfString - 1);
}
});
This works for adding the string only once. But when I deselect all of the options so that there are 0
selections.. I get this:
Unable to get property 'indexOf' of undefined or null reference
On this line: var indexOfString = $("#MyTextArea").value.indexOf(string);
Any help is appreciated.
It should be :
var indexOfString = $("#MyTextArea").val().indexOf(string);
Because $("#MyTextArea")
is a jQuery element
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments