Javascript 如何通过javascript从下拉列表中获取选定的值并设置在java bean中选择的值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13966150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get the selected value from dropdown list through javascript and set the value selected in java bean?
提问by Lucky
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.
如何使用 Javascript 获取所选下拉列表值的当前值?
我有一个用户联系表单,其中有一个下拉列表,列表中选择的值必须由 javascript 函数捕获,然后将此值传递给控制器并设置 bean 值,然后将该值保留在数据库中。
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 selectedbe val2
这将使selected是val2
How do I access this value in Java class and store the value in database?
如何在 Java 类中访问此值并将该值存储在数据库中?
回答by Avinash Nair
Submit your form to a servlet
将您的表单提交给 servlet
to fetch the selected value, use this code in your servlet
要获取选定的值,请在您的 servlet 中使用此代码
String str=(String)req.getParameter("selectboxname");
String str=(String)req.getParameter("selectboxname");
回答by Lokesh
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;
回答by Lucky
I handled the request with ajax call and transferred control to a Spring Controller..I wrote this code in my controller..
我使用 ajax 调用处理请求并将控制权转移到 Spring 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...
现在终于按预期工作了......

