I’m trying to get data which is selected inside of a multiselect. However, I want to display the selected options inside another field in the form. Therefor I don’t want to send the actual form before getting the data and displaying it.
I want to use the value mainly to gather information from a database which gives the user a amount specified for that select option!
I have tried multiple different solutions from different threads but unfortunately they haven’t worked!
Select which i want to gather the selected options from:
JavaScript
x
9
1
<div class="col-12">
2
<label for="misstanke" class="form-label">Lagöverträdelser</label>
3
<select multiple name="misstanke[]" onkeydown="return event.key != 'Enter';" class="form-select form-select-md">
4
<?php
5
include('selects/overtradelser.php');
6
?>
7
</select>
8
</div>
9
Input field I want to display the data in:
JavaScript
1
5
1
<div class="mb-3">
2
<label for="straff" class="form-label">Påföljder</label>
3
<input type="text" onkeydown="return event.key != 'Enter';" class="form-control" name="straff" id="straff">
4
</div>
5
Code:
JavaScript
1
9
1
function Straff() {
2
var select1 = document.getElementById("misstanke");
3
var selected1 = [];
4
for (var i = 0; i < select1.length; i++) {
5
if (select1.options[i].selected) selected1.push(select1.options[i].value);
6
}
7
document.getElementById("straff").setAttribute('value', select1);
8
}
9
Advertisement
Answer
To update the value of an input, assign to its value
property, not the attribute.
You should use the join()
method to convert the array to a string with a specified delimiter.
JavaScript
1
2
1
document.getElementById("straff").value = selected1.join(',');
2