Remie Remie - 28 days ago 7
Javascript Question

JS - how to remove or replace text value in textarea after choosing new value

Fiddle

I have a textarea and two dropdowns. Each dropdown has 4 possible values. After a value is selected, its value appears as text in the textarea.

My problem is that if you change the value selected from one of the dropdowns then it just ADDS the new value to the textarea instead of REPLACING the previously selected value.

Is there a way of DELETING or REPLACING the previously added value within the textarea?

(and without deleting/replacing the value populated from the other dropdown)

var mytextbox = document.getElementById('mytext');
var mydropdown = document.getElementById('dropdown');

mydropdown.onchange = function(){
mytextbox.value = mytextbox.value + "\n" + this.value;mytextbox.rows = mytextbox.rows + 1;mytextbox.style.height = (mytextbox.rows * 30) + 'px';
}

var mytextbox = document.getElementById('mytext');
var mydropdown = document.getElementById('dropdown2');

mydropdown.onchange = function(){
mytextbox.value = mytextbox.value + "\n" + this.value;mytextbox.rows = mytextbox.rows + 1;mytextbox.style.height = (mytextbox.rows * 30) + 'px';
}

Answer

Is there a way of DELETING or REPLACING the previously added value within the textarea?

Yes the way is to just assign the value to the textbox, no need to append it or concatenate it with the old value, so remove the mytextbox.value + "\n" part :

mytextbox.value = mytextbox.value  + "\n" + this.value;

Should be :

mytextbox.value = this.value;

Hope this helps.

var mytextbox = document.getElementById('mytext');
var mydropdown1 = document.getElementById('dropdown');
var mydropdown2 = document.getElementById('dropdown2');
var mydropdown1_value = mydropdown1.value;
var mydropdown2_value = mydropdown2.value;

mydropdown1.onchange = function(){
  mydropdown1_value = mydropdown1.value;

  mytextbox.value = mydropdown1_value + '\n' + mydropdown2_value;
}

mydropdown2.onchange = function(){
  mydropdown2_value = mydropdown2.value;

  mytextbox.value = mydropdown1_value + '\n' + mydropdown2_value;
}
<div class="expandingArea">
  <textarea id="mytext"></textarea>
</div>
<select id="dropdown">
  <option value="">None</option>
  <option value="text1">text1</option>
  <option value="text2">text2</option>
  <option value="text3">text3</option>
  <option value="text4">text4</option>
</select>
<select id="dropdown2">
  <option value="">None</option>
  <option value="textA">textA</option>
  <option value="textB">textB</option>
  <option value="textC">textC</option>
  <option value="textD">textD</option>
</select>

Comments