0

I have a dropdown list which is dynamic so how can I iterate and insert the list values in the dropdown list?

var questionids = {"Name", "Age", "Smoker", "Drinker", "Visit Denist"};

<select name="questionid" id="questionids">
<c:forEach var="questionids" items="${questionids}">
<option value="">${questionids}</option>
</c:forEach>
</select>

I tried as mentioned above. it is not working. Also I need the value of each option should auto increment like, For first option value is 1 and second option value is 2. e.t.c

Can any one please suggest the solution please

Vinod
  • 2,263
  • 9
  • 55
  • 104
  • Take a look at this post http://stackoverflow.com/questions/18740616/load-the-drop-down-list-dynamically-using-jstl – JHDev Jun 23 '15 at 11:23

3 Answers3

0

This is right approach but you have to give another name to var in <c:forEach> like below:

var questionids = {"Name", "Age", "Smoker", "Drinker", "Visit Denist"};

<select name="questionids" id="questionids">
    <c:forEach var="questionid" items="${questionids}">
        <option value="${questionid}">${questionid}</option>
    </c:forEach>
</select>
vivekpansara
  • 895
  • 1
  • 6
  • 14
0
<% java.util.HashMap map = new java.util.HashMap(); 
map.put("0", "Name"); 
map.put("1", "Age"); 
map.put("2", "Smoker"); 
map.put("3", "Drinker"); 
map.put("4", "Visit Denist"); 
pageContext.setAttribute("map", map); 
%>




<select name="questionid" id="questionids" >
    <c:forEach items="${map}">
        <option value="${items.key}">${items.value}</option>
    </c:forEach>
</select>
kavetiraviteja
  • 2,058
  • 1
  • 15
  • 35
  • I tried this, But no values are showing under the dropdown list – Vinod Jun 23 '15 at 13:03
  • have you include the above taglib's ?? I have tested above code it is working fine for me... can you give some broad explanation to your problem. – kavetiraviteja Jun 23 '15 at 13:06
  • Yes, It is working now. But I don't need the value to be question text. I need the auto increment numbers for questions like. For first question the value should be 1 and for second the value should be 2 e.t.c – Vinod Jun 23 '15 at 13:30
  • I am not clear with your suggestion. Can you please explain more on it, Please – Vinod Jun 23 '15 at 14:22
0
<select name="questionid" id="questionids">
</select>

You can build select using javascript dynamically. You may want to use arr value as option value. If you want to use increment you can create a arr and loop them.

    var questionids = {"Name", "Age", "Smoker", "Drinker", "Visit Denist"};
//  var valuesArr = [1, 2, 3, 4, 5];       
    $.each(questionids , function(i, e) {
        $('#questionids').append("<option value='"+e+"'>"+e+"</option>");
//      $('#questionids').append("<option value='"+valuesArr[i]+"'>"+e+"</option>");
    });
He Zhang
  • 137
  • 2
  • 16