Skip to content
Advertisement

How do you retrieve selected options BEFORE the user have submitted the form?

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:

<div class="col-12">
  <label for="misstanke" class="form-label">Lagöverträdelser</label>
  <select multiple name="misstanke[]" onkeydown="return event.key != 'Enter';" class="form-select form-select-md">
    <?php
    include('selects/overtradelser.php');
    ?>
  </select>
</div>

Input field I want to display the data in:

<div class="mb-3">
  <label for="straff" class="form-label">Påföljder</label>
  <input type="text" onkeydown="return event.key != 'Enter';" class="form-control" name="straff" id="straff">
</div>

Code:

function Straff() {
    var select1 = document.getElementById("misstanke");
    var selected1 = [];
    for (var i = 0; i < select1.length; i++) {
        if (select1.options[i].selected) selected1.push(select1.options[i].value);
    }
    document.getElementById("straff").setAttribute('value', select1);
}

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.

document.getElementById("straff").value = selected1.join(',');
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement