How can I get the current value of a selected dropdown list value using Javascript?
I have a user contact form in which I have a dropdown list and the value selected in the list must be captured by javascript function and then pass this value to the controller and set the bean value and then persist the value in database.
The list is like,
<select id="ddl">
<option value="val1">Optoion 1</option>
<option value="val2" selected="selected">Option 2</option>
<option value="val3">Option 3</option>
</select>
To return the string from the list
var e = document.getElementById("ddl");
var selected = e.options[e.selectedIndex].val();
Which would make selected
be val2
How do I access this value in Java class and store the value in database?
Submit your form to a servlet
to fetch the selected value, use this code in your servlet
String str=(String)req.getParameter("selectboxname");
If you want to get value of select value of drop down then use this
document.getElementById("ddlViewBy").value;
If you want to get text of select index then
document.getElementById("ddlViewBy").options[document.getElementById("ddlViewBy").selectedIndex].text;
I handled the request with ajax call and transferred control to a Spring Controller..I wrote this code in my controller..
@Controller
public class ContactController{
@RequestMapping(value = "/contact/processContact", produces = "application/json")
public @ResponseBody Map<String, Object> processWriteToUs(@ModelAttribute("contact") Contact contact,HttpServletRequest request, HttpServletResponse response, Model model){
Map<String, Object> responseMap = new HashMap<String, Object>();
try {
Contact contact = new Contact();
contact.setEmail(request.getParameter("email"));
contact.setFirstName(request.getParameter("firstname"));
contact.setLastName(request.getParameter("lastname"));
contact.setType(request.getParameter("ddl"));
//process the form details...
//responseMap.put("key","value")
}
catch{Exception e){
e.printStackTrace();
}
return responseMap;
}
}
and now finally that works as expected...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.