Two HTML-select boxes linked to each other with data in text area

时间:2018-07-24 10:02:33

标签: javascript textarea html-select

I have extended Leo's answer to the original question 27673937 (two HTML-select boxes linked to each other) to include placing the selected variable sel2 into a textarea. What I am struggling with is getting the textarea to update when sel2 is changed after sel1 is changed. It will update if sel1 is changed but not sel2. Update: SOLVED this myself. The answer is:

<html>
<head>
</head>
<body>

<br><br>

<select id="sel1" onChange="giveSelection(this.value)">
<option value="a">a</option>
<option value="b">b</option>
<option value="c">c</option>
<option value="d">d</option>
</select>

<select id="sel2" onChange="updateSelection(this.value)">
  <option data-option="a">alpha</option>
  <option data-option="a">airplane</option>
  <option data-option="a">apple</option>
  <option data-option="b">bravo</option>
  <option data-option="b">book</option>
  <option data-option="c">charlie</option>
  <option data-option="c">cobana</option>
  <option data-option="d">delta</option>
  <option data-option="d">delphine</option>
</select>

<br><br>
<form name="form-jobdetails">
<textarea name="initialText" cols="70" rows="7"></textarea>
</form>


<script type="text/javascript">
var sel1 = document.querySelector('#sel1');
var sel2 = document.querySelector('#sel2');
var options2 = sel2.querySelectorAll('option');

//link second drop down to first
function giveSelection(selValue) {
  sel2.innerHTML = '';
  for(var i = 0; i < options2.length; i++) {
  if(options2[i].dataset.option === selValue) {
  sel2.appendChild(options2[i]);

// populate the form
document.forms['form-jobdetails']['initialText'].value = (sel2.value);    

    }
  }
}

giveSelection(sel1.value);
// end of first block of code

// and if the second drop down is changed
function updateSelection(selValue) {
// re populate the form
document.forms['form-jobdetails']['initialText'].value = (sel2.value);  

  }

</script>


</body>
</html>

0 个答案:

没有答案