How to insert an array of String into Selectpicker in HTML

Viewed 317

Im trying to introduce the Array of Strings shown below into a Selectpicker so the options of the selectpicker would be the elements of the array.

<script>
        String str[] = (String[]) request.getAttribute("intervenciones"); 
        for (var i=0;i<str.length;i++){
            option += '<option value="'+ str[i] + '">' + str[i] + '</option>';
        }
        $('#procedimiento').append(option);
</script>
<div class="row top-buffer">
    <div class="col-sm-4">
    <label for="procedimiento">Procedimiento</label>                                
    <select name="procedimiento" id="procedimiento" class="form-control selectpicker" data-show-subtext="true" data-live-search="true" data-size="3" style="width: 100px;">
    </select>

</div>
2 Answers

Well, I dont know what data-show-subtex and so is but I think it is for some jquery plugin.

If that is the code you are running, it wont work because in Javascript you dont declare variables like that.

You should change your code to this:

// change this for request.getAttribute(...)
var options = ['option1', 'option2', 'option3'];
var option = '';
for (var i=0;i<options.length;i++){
    option += '<option value="'+ options[i] + '">' + options[i] + '</option>';
  }
$('#procedimiento').append(option);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row top-buffer">
    <div class="col-sm-4">
    <label for="procedimiento">Procedimiento</label>                                
    <select name="procedimiento" id="procedimiento" class="form-control selectpicker" data-show-subtext="true" data-live-search="true" data-size="3" style="width: 100px;">
    </select>

</div>

You can use jstl forEach loop to print values inside your select-box .i.e :

<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
 <select name="procedimiento" id="procedimiento" class="form-control selectpicker" data-show-subtext="true" data-live-search="true" data-size="3" style="width: 100px;">
    <c:forEach var="inter" items="${intervenciones}" > //<-pass your value here which set in requst attribute
             <option value="${inter}">${inter}</option>//<-printing options
     </c:forEach>
 </select>
Related