I want to copy multiselect options to textarea. I wrote code and it goes well up till I change value in textarea box for example when I add something. After adding additionaly characters to textarea JS coping function don't work. Why? This is code:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form >
<div >
<div >Multiselect:<br/>
<select id="source_select" multiple="multiple" style="width: 500px; height:200px">
<option value="option 1"> option 1 </option>
<option value="option 2"> option 2 </option>
<option value="option 3"> option 3 </option>
<option value="option 4"> option 4 </option>
<option value="option 5"> option 5 </option>
</select>
</div>
<div ><br/><br/>Textarea:<br/>
<textarea name="text_to_db" id="target_textarea" style="width: 500px; height:200px"></textarea>
</div>
</div>
<div >
<div ><br/>
<button type="button" onclick="myFunction()">Copy multiselect to textarea</button>
</div>
</div>
</form>
<script>
function myFunction() {
if (document.getElementById("source_select").length > 0) {
for (let i=0; i < document.getElementById("source_select").length; i ){
const option = document.getElementById("source_select").options[i];
const value = option.value;
if (option.selected) {
let nowy_tekst = document.getElementById("target_textarea").innerHTML value ", ";
document.getElementById("target_textarea").innerHTML = nowy_tekst;
// option.remove();
}
}
}
}
</script>
</body>
</html>
CodePudding user response:
You should use .value
instead of .innerHTML
since textarea
is a form element.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form >
<div >
<div >Multiselect:<br/>
<select id="source_select" multiple="multiple" style="width: 500px; height:200px">
<option value="option 1"> option 1 </option>
<option value="option 2"> option 2 </option>
<option value="option 3"> option 3 </option>
<option value="option 4"> option 4 </option>
<option value="option 5"> option 5 </option>
</select>
</div>
<div ><br/><br/>Textarea:<br/>
<textarea name="text_to_db" id="target_textarea" style="width: 500px; height:200px"></textarea>
</div>
</div>
<div >
<div ><br/>
<button type="button" onclick="myFunction()">Copy multiselect to textarea</button>
</div>
</div>
</form>
<script>
function myFunction() {
if (document.getElementById("source_select").length > 0) {
for (let i=0; i < document.getElementById("source_select").length; i ){
const option = document.getElementById("source_select").options[i];
const value = option.value;
if (option.selected) {
let nowy_tekst = document.getElementById("target_textarea").value value ", ";
document.getElementById("target_textarea").value = nowy_tekst;
// option.remove();
}
}
}
}
</script>
</body>
</html>