【问题标题】:How to validate select option for a Materialize dropdown?如何验证 Materialize 下拉菜单的选择选项?
【发布时间】:2015-12-13 07:25:09
【问题描述】:

我有一个使用 materializecss 的基本选择框。

<select id="type" name="type" required="required" class="validate">
    <option value="" disabled="true" selected="selected">Choose your option</option>
    <option value="general">General</option>
    <option value="tech">Tech</option>
    <option value="person">Personnel</option>
    <option value="resource">Resourcing</option>
</select>
<label data-error="Select an option">Type of Question</label>

我希望用户在提交表单之前选择一个选项。

如果用户没有选择选项,我怎样才能让它显示标签的data-error

【问题讨论】:

    标签: html materialize


    【解决方案1】:
    $("select[required]").css({display: "block", height: 0, padding: 0, width: 0, position: 'absolute'});
    

    【讨论】:

    • 完美答案。
    • 您可以添加 left: 50% 以便警告文本出现在选择字段的中间。
    【解决方案2】:

    我遇到了类似的问题。我很少搜索我找到了一个简单的解决方案:

    第 1 步:

    material_select 隐藏您的选择 (display: none)。正如this post 中提到的,jQuery 验证器会忽略隐藏字段。因此,作为提到的解决方法,在 validate 方法之前添加以下内容:

    $.validator.setDefaults({
           ignore: []
    });
    
    $("#yourForm").validate({
            errorClass: "invalid form-error",       
            errorElement : 'div',       
            errorPlacement: function(error, element) {
                error.appendTo( element.parent() );
            }
    });
    

    还要注意 form-error 类是我的 css 中的自定义类:

    .form-error{color: #D8000C;}
    

    第 2 步:

    使您的选择成为必填项,该选项已应用于此问题的select 标记。或者,您可以在validate 方法的规则中将您的选择标记添加为required: true。但这不是必需的,如果您在 html 选择标签中添加了required,那就可以了。

    就是这样。这样,当提交表单或调用$("#yourForm").valid() 时,它将验证您的选择。

    【讨论】:

      【解决方案3】:

      捎带上一个答案,我发现添加可见性隐藏属性有助于清理事情

        $("select[required]").css({
          display: "block", 
          position: 'absolute',
          visibility: 'hidden'
        })
      

      【讨论】:

        【解决方案4】:

        希望这会有所帮助:

        $('form').on('submit',function(e){
            $(".error_note").remove();
            var select = $(this).find('select').filter("[required=required]");
            $.each(select , function(index, elm){
                val = $(this).val();    
                target = $(this).closest('.input-field');
                if (typeof target !== "undefined") {
                    input_target = target.find('input.select-dropdown');
                    if (typeof input_target !== "undefined") {                  
                        if(val == '' || val == false || val == 0 || val == null){
        
                            input_target.css({'border-color':'#EA454B','box-shadow':'0 1px 0 0 #EA454B'});
                            input_target.after('<span class="error_note" style="color: #EA454B;font-size: 12px;">Please select this field.</span>');
        
                            $('html,body').animate({ scrollTop: $("body").offset().top},'slow' );
                            e.preventDefault();
        
                        }else{
                            input_target.css({'border-color':'#9e9e9e'});
                        }
        
                    }
                }           
            });
        });
        

        【讨论】:

          【解决方案5】:
          $("select[required]").css({display: "inline", height: 0, padding: 0, width: 0});
          

          【讨论】:

            【解决方案6】:

            hemu 的回答帮助我在物化论坛上进行了一些讨论。我想出了这个很好地集成的解决方案。诀窍是正确定位错误标签并为其赋予颜色:

            .select-wrapper label.invalid {
                margin-top: 62px;
                margin-left: -11px;
                color: #F44336;
            }
            

            您可以在下面的 Fiddle 中找到这个以及更多错误放置技巧:

            http://jsfiddle.net/b8frk03m/6/

            【讨论】:

              【解决方案7】:

              这对我来说效果更好,不需要 JavaScript,只需一些简单的 CSS:

              select[required]:focus{
                  outline: none !important;
              }
              
              select[required]{
                  display: block;
                  padding: 0;
                  position: absolute;
                  background: transparent;
                  color: transparent;
                  border: none;
                  top: 0;
              }
              

              【讨论】:

                【解决方案8】:

                最终解决方案

                问题实际上在于渲染的input 替换了select 元素。此选择是否隐藏无关紧要。 Materialize CSS 引擎不会验证您的选择元素是否是必需的或具有validate 类。我不知道他们为什么没有把我将在下面展示给你的代码,但是如果你把它放在你页面中的 JavaScript 文件中,这将解决问题:

                <script>
                $(document).ready(function(){
                    $('.tooltipped').tooltip(); // dica que aparece quando o usuário põe o mouse em cima do componente
                    $('select').formSelect(); // montagem de campos <select> com material design
                    // isto corrige o problema de renderização em campos select que exigem validação quando o campo é de preenchimento obrigatório
                    const _requiredSelects = $("select[required].validate");
                    _requiredSelects.parent().find('input').addClass('validate').attr('required', true)
                    .keydown(function($event) { 
                        return $event.keyCode == 9;
                    });
                    _requiredSelects.change(function($event) { 
                        const _select = $event.target;
                        const _value = $(_select).val();
                        const _input = $(_select).parent().find('input');
                        _input.removeAttr('readonly', '');
                        _input.val(_select.options[_select.options.selectedIndex].label);
                        if (_value != '') {
                            _input.addClass('valid');
                            _input.removeClass('invalid');
                        } else {
                            _input.addClass('invalid');
                            _input.removeClass('valid');
                        }
                    });
                    _requiredSelects.each(function(){
                        const _this = $(this);
                        const _helper = _this.parent().parent().find('.helper-text');
                        if (_helper !== undefined) {
                            const _input = _this.parent().find('input');
                            _helper.insertAfter(_input);
                        }
                    });
                });
                </script>
                

                【讨论】:

                  猜你喜欢
                  • 2015-05-04
                  • 2015-02-06
                  • 2012-12-03
                  • 2017-06-29
                  • 1970-01-01
                  • 2016-07-20
                  • 1970-01-01
                  • 2014-11-28
                  相关资源
                  最近更新 更多