0

I am trying to match one className called invalid. My classes have a default class of 'form-control' and another which is concatenated to the class by the class called ' invalid' if a mandatory field has not been supplied with data which makes 'form-control invalid.

My code works but I would like it to be more efficient by matching only the 'invalid' class and not the whole 'form-control invalid'.

if (txtCust.className != 'form-control invalid') {
btnSave.onclick = ""; 
}
Tom McDonough
  • 1,176
  • 15
  • 18
  • 1
    Try `txtCust.classList.contains('invalid')` to check if the target has class `invalid` or not. And here's some doc of [Element.classList](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList). – fuyushimoya Sep 09 '15 at 14:42
  • possible duplicate of [Test if an element contains a class?](http://stackoverflow.com/questions/5898656/test-if-an-element-contains-a-class) – fuyushimoya Sep 09 '15 at 14:56
  • Thank you fuyushimoya, you have resolved my issue. – Tom McDonough Sep 09 '15 at 15:07

1 Answers1

0
if(txtCust.className.indexOf('invalid') < 0)

The indexOf() method will return the starting index of the substring's starting point within a String. So for example:

String hello = 'hello';
hello.indexOf('el'); //would return 1

So if indexOf returns a number greater or equal to 0 then that means the substring exists within the String. If it's less than 0 (usually -1), it means that the String doesn't contain the substring you are looking for.

cbender
  • 2,231
  • 1
  • 14
  • 18