简体   繁体   English

如何使用户选择下拉框选项?

[英]How to make user to choose an option of dropdown box?

I am using the following answer to implement a required dropdown box. 我正在使用以下答案来实现所需的下拉框。 The only difference is that the code of dropdown box in my application is in a new page which will be popped up. 唯一的区别是我的应用程序中下拉框的代码在一个新页面中,该页面将会弹出。

The problem is that once user select any option including the one with none value, the form gets submitted! 问题是,一旦用户选择任何选项(包括无值的选项),就将提交表单!

Page 1 第1页

   <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate
                                                         /1.9/jquery.validate.js"
                                                        </script>
   <script type="text/javascript">

          $("#everything").validate({
              messages: {
                  dd1: {
                     required: "Please select an option from the list, if 
                                none are appropriate please select 'Other'"
                }
            }
          });
          function popup(){
             document.getElementById("mydropbox").style.display = "Block";
              >> send request to server to show the Page 2 in body of mydropbox <<
             return false;
          }
   </script>

</head>
<body>

    <a href="" OnClick="return popup()">popup</a>

    <div id="mydropbox"></div>
...  
</body>
</html>

page 2 第2页

<html>
 <body>
    <form id="everything">
             <label for="dd1">Select the best option</label><br/>
             <select name="dd1" id="dd1" class="required">
                 <option value="">None</option>
                 <option value="o1">option 1</option>
                 <option value="o2">option 2</option>
                 <option value="o3">option 3</option>
             </select> 
             <br/><br/>
             <input type="submit" />
   </form>
 </body>
</html>

Add the required attribute to your select element. required属性添加到您的select元素。 That should work in modern browsers at least. 至少应该在现代浏览器中有效。

It alerts the user if the option they are selecting has an empty value (like the option "None" in your case). 如果用户选择的选项具有空值(例如您的情况下的“无”),它将提醒用户。 You would have do do server-side validation too of course, because you can't rely on this. 当然,您也将做服务器端验证,因为您不能依靠它。

Updated Demo 更新的演示

HTML 的HTML

<input type="submit" id="sbt" /> //added id to the submit button sbt

js js

$('#sbt').click(function (e) {
    e.preventDefault(); //stop form submit
    if ($('#dd1 option:selected').text() != 'None') {
        $('#everything').trigger('submit'); // if selected text not = to None then trigger form submit.
    }
});

DEMO 演示

Remove the submit button from the form and use this 从表单中删除“提交”按钮并使用它

form will be submitted only if the dropdownlist value is changed 仅当dropdownlist值更改时,才会提交表单

<select onchange="this.form.submit()">
    ...
</select>

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

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