albuvee albuvee - 3 months ago 9
CSS Question

jQuery: check if element has specific style (not inline)

Is it possible to check via jQuery or vanilla JS if an element has a specific style?

In my case I want to check if any input-fields on the page have a red border — applied via an external CSS-File. No inline-css and no

style
-attr is available, styling is completely external.

For my initial testing I got the following code from this StackOverflow-Answer: http://stackoverflow.com/a/29659187

$('.formValidation input[type=submit]').on('click',function(e){
e.preventDefault();
var res = $('.formValidation input[type=text],.formValidation input[type=email],.formValidation input[type=url],.formValidation input[type=password]').toArray().some(function(el){
return $(el).css('border-color') === 'rgb(255,0,0)'
});
if (res) {
console.log('Still at least one field to go!');
} else {
console.log('You can submit!');
}
});


… but .css seams to only test inlineStyles.

Update
I can't change HTML, the markup has to stay «as is». The red border is coming through css only. Like this: https://jsfiddle.net/z3t6k04s/

Answer

Try it like this:

 $('.formValidation input[type=submit]').on('click',function(e){
        // Prevent Default Form Submit
         e.preventDefault();

        // Define Global if Invalid Fields Exist
        var hasInvalidInputs = false;

        // Run Through all to check Input Fields
        $('input').filter(function(index){

          // Check if Invalid Inputs already got detected. If not - check if this field is red
          if( !hasInvalidInputs )
            hasInvalidInputs = $(this).css('border-color') == 'rgb(161, 0, 0)';     // If field is red -> update global var to true
          });

        // Check if Invalid Fields are set to true
        if (hasInvalidInputs) {
          console.log('Still at least one field to go!');
        } else {
          console.log('You can submit!');
        }
    });