【问题标题】:How to validate that the user selected in select form如何验证用户在选择表单中选择
【发布时间】:2016-04-13 17:49:43
【问题描述】:

我有选择表格:

<form method="post" name="posting_txt" onSubmit="return blank_post_check();" id="post_txt">
        <select  style="background: transparent; border-bottom:5px;" name="subname" class="required">                           
            <option value="" > Choose subject </option> 
            <option value="aaa" > AAA </option>     
            <option value="bbb" > BBB </option>
        </select> 
    <input type="submit" value="post" name="txt" class="btn" id="post_button" onClick="time_get()">
</form>

如果用户按下“发布”,但没有选择主题,我想放置警报标签

编辑-感谢 maihan 的回答,我可以修复它:

   function time_get()
   {
        var selected = document.getElementById("select_post_id");
        var selectedVal = selected.options[selected.selectedIndex].value;
       if(selectedVal != ""){
          //do whatever
       }else{alert('select an option');}
    }

【问题讨论】:

    标签: javascript jquery html ajax jquery-plugins


    【解决方案1】:

    将逻辑放在您拥有的time_get() 函数中。

    if(document.getElementsByTagName(select).value ==''){
          alert("Select an option")
    }
    

    【讨论】:

      【解决方案2】:

      如果选择没有值,您可以在表单上添加事件处理程序以防止提交它,然后显示警报或添加/取消隐藏警告&lt;label&gt;

      $('form#post_txt').submit(function(event){
          var subname = $('select[name="subname"]').val()
          if(subname === null || subname === "") {
              event.preventDefault();
              //warn user
          }
      });
      

      我还建议在您的第一个选择选项中添加selected="selected" 作为属性,以便从一开始就选择它,而不是空白选择。

      【讨论】:

        【解决方案3】:

        Maihan 的回答很好,但为了改进,我会将“Choose Subject”的值设为“NULL”,然后使用 if 语句进行验证

        <form method="post" name="posting_txt" onSubmit="return blank_post_check();" id="post_txt">
            <select  style="background: transparent; border-bottom:5px;" name="subname" class="required">                           
                <option value=NULL > Choose subject </option> 
                <option value="aaa" > AAA </option>     
                <option value="bbb" > BBB </option>
            </select> 
        <input type="submit" value="post" name="txt" class="btn" id="post_button" onClick="time_get()">
        

        那么……js……

        function time_get(){
           if(document.getElementByClassName(required) != NULL){
              //do whatever
           }else{alert('select an option')}
        }
        

        【讨论】:

          猜你喜欢
          • 2017-12-27
          • 1970-01-01
          • 1970-01-01
          • 2010-10-23
          • 1970-01-01
          • 2017-05-10
          • 2011-04-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多