如何以编程方式覆盖表单提交中的select2 CSS?

时间:2019-01-29 22:48:04

标签: jquery css css-selectors jquery-select2

我正在尝试突出显示用户尝试提交表单时未填写的select2选择。我无法弄清楚如何从文档加载中覆盖现有的CSS样式。

这是我的jquery尝试:

var $requiredUnfilledItems = $(".required:not(.filled)");
if ($requiredUnfilledItems.length > 0) {
  $requiredUnfilledItems.each( function(){
    $(this).addClass('warning-border');
  });
}

和我的.warning-border的CSS:

.warning-border { 
    outline: none !important;
    border-color: red !important;
    box-shadow: 0 0 10px red !important;
}

正在尝试覆盖此内容:

.select2-container--default .select2-selection--single {
    width: 100%;
    padding-left: 4px;
    height: 100%;
    border: thin solid lightgray;
    height: 30px;
}

但是它不起作用。我也试过了(可能只是证明我还没有掌握CSS):

.warning-border, .select2-container.warning-border { 
    outline: none !important;
    border-color: red !important;
    box-shadow: 0 0 10px red !important;
}

帮助?

1 个答案:

答案 0 :(得分:0)

我的建议是不要使用!important,而是要了解CSS是如何级联的……在Web上比我有更好的资源-

https://developer.mozilla.org/en-US/docs/Learn/CSS/Introduction_to_CSS/Cascade_and_inheritance

在我的示例代码段中,我随意制作了一个JQuery处理程序,因此文本输入字段知道何时填充它,并在onkeyup上向其自身添加(或删除)一个填充的类-您应该为此添加处理程序,除非一个已经在代码中的某个地方触发了(我猜你已经这样做了)。

我将这些类组合添加到CSS中,以使它们不会以红色突出显示(在片段的样式表底部)。

您使用的是border-color,但是您要覆盖的实际属性在CSS中是简写形式,因此我对其进行了切换,因此它们都是简写形式,并保证会影响相同的属性。我不记得它是如何工作的,但这可能是一个问题...

$( "input[type=text]" ).keyup(function() {
  if(this.value != '') $(this).addClass('filled');
  else
    $(this).removeClass('filled')
});

$("form").submit(function(){
  var $requiredUnfilledItems = $('.required:not(.filled)'); 
  if ($requiredUnfilledItems.length > 0) 
  {$requiredUnfilledItems.each( function(){$(this).addClass('warning-border');
   });
  }
  else { alert("You entered in " + this.name.value); }
  return false;})
.warning-border { 
    outline: none !important;
    border: thin solid red;
    box-shadow: 0 0 10px red;
}

.warning-border, .select2-container.warning-border { 
    outline: none !important;
    border: thin solid red;
    box-shadow: 0 0 10px red;
}

.warning-border.filled, .select2-container--default .select2-selection--single {
    width: 100%;
    padding-left: 4px;
    height: 100%;
    border: thin solid lightgray;
    height: 30px;
    box-shadow: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="#" onsubmit="">
<input id="name" type="text" class="required filled" value="Name"/>
<input type="submit">
</form>

相关问题