简体   繁体   English

如何通过javascript从下拉列表中获取选定的值并设置在Java bean中选择的值?

[英]How to get the selected value from dropdown list through javascript and set the value selected in java bean?

How can I get the current value of a selected dropdown list value using Javascript? 如何使用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函数捕获,然后将此值传递给控制器​​并设置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 selected be val2 这将使selectedval2

How do I access this value in Java class and store the value in database? 如何在Java类中访问此值并将该值存储在数据库中?

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"); 

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.. 我用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... 现在终于可以按预期工作了...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM