Alina
Alina

Reputation: 27

JSP: How to pass all (selected and unselected) options of a dropdown list to servlet?

I have a dropdown list in my JSP web app, and I add and remove items from an input text to it using the JavaScript code. Now, I want to pass all (selected and unselected) items of the dropdown list to a servlet using the submit button. How do I do it? The following code only returns the value of the selected item:

String ST=request.getParameter("friendList");

My HTML and JavaScript Codes:

<form class="form" action="project" method="post">
<input type="text" id="In_Name" placeholder="my new friend's name"/>
<div class="addIcon" onclick="addFriend()"></div>
<div class="removeIcon" onclick="removeFriend()"></div>
<select size="5" name="friendList" id="friendList">
</select>
<button type="submit" name="MyButton">Submit</button>
</form>

<script>
function addFriend() {
    var Str=document.getElementById("In_Name").value;
    if(Str!="")
    {
        var opt = document.createElement("option");
        opt.text = Str;
        opt.value = Str;
        document.getElementById("friendList").options.add(opt);
    }
}
function removeFriend() {
    var x = document.getElementById("friendList");
    if(x.selectedIndex != "-1")
        x.remove(x.selectedIndex);
}
</script>

Upvotes: 1

Views: 1332

Answers (2)

Avinash Thakur
Avinash Thakur

Reputation: 81

You have already used name attribute.So you just need to add one line to your servlet. And add one more attribute to your jsp file "multiple".

use : String values[]=request.getParameterValues("friendList");

Upvotes: 0

user2575725
user2575725

Reputation:

I want to pass all (selected and unselected) items of the dropdown list to a servlet using the submit button

Browsers, will only pass on selected options, in order to send all options, use multiple attribute. Also you will need a handy script to select all options before form submit.

Change in servlet:

String[]ST=request.getParameterValues("friendList");

JSP changes:

<form class="form" action="project" method="post" onsubmit="selectAll('friendList')">
    ....
    <select size="5" name="friendList" id="friendList" multiple=''></select>
    ....
</form>

<script>
...
function selectAll(id){
   var options = document.getElementById(id).options;
   var len = options.length;
   while(len --){
      options[len].selected = true;
   }
}
</script>

Upvotes: 2

Related Questions