I have a function that I am using to append data elements from one dropdown option to another
The function is working properly. What I am looking for is to get the values of the second dropdown option which is an array
<select id="sel1" multiple size="5">
<option value="test1">1st test</option>
<option value="test2">2nd test</option>
<option value="test3">3rd test</option>
<option value="test4">4th test</option>
<option value="test5">5th test</option>
</select>
<select id="sel2" name = "sel2[]" multiple size="4">
<option value="dummy">Dummy</option>
</select>
<br>
<input type="button" id="doBtn" value="do it">
<input type="button" id="submit" value="add">
and this is my javascript for appending elements
$('#doBtn').click(function () {
$('#sel1 option:selected').each(function () {
$("<option/>").
val($(this).val()).
text($(this).text()).
appendTo("#sel2");
});
});
when I submit it, I expect the $diag_string to have values but it returns empty
if(isset($_POST[submit]))
{
$diag_string = implode(', ', $_POST['sel2']);
$sql ="INSERT INTO ...... values ('...... ')";
$qsql = mysqli_query($con,$sql);
}
what has to be done to sel2[] select option to obtain values from it?
>Solution :
Options are being appended, but they’re not being selected. So when the form submits, sel2 has no selected options.
You can select them by setting a .val() on the target element after appending the options. For example:
$('#doBtn').click(function () {
$('#sel1 option:selected').each(function () {
$("<option/>").
val($(this).val()).
text($(this).text()).
appendTo("#sel2");
});
// set the value here
$('#sel2').val($('#sel1').val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<select id="sel1" multiple size="5">
<option value="test1">1st test</option>
<option value="test2">2nd test</option>
<option value="test3">3rd test</option>
<option value="test4">4th test</option>
<option value="test5">5th test</option>
</select>
<select id="sel2" name = "sel2[]" multiple size="4">
<option value="dummy">Dummy</option>
</select>
<br>
<input type="button" id="doBtn" value="do it">
<input type="button" id="submit" value="add">
Alternatively, if you want all options to be selected, you could do that too.