Search code examples
javascripthtmlcssclassname

adding className is not working on a particular field


I have a function that checks if a field is empty. if it is it will assign an error class that paints it red. it works on all the fields of my form but one. on that one it just adds the class attribute to the element without any value.

this is my function

function validateEmptyPass(pass) {
    var a = $('#password-conf');
    var error = "";
    var fieldName;
    if (a[0].value.length === 0) {
        a[0].className ="errorField"
        error= "password field empty"
    } else {
        a[0].className = '';     
    }
    return error;   

this is what happens to the element.

<input id="password-conf" name="passwordConf" rel="Password Confirmation" placeholder="password confirmation" type="password" maxlength="25" tabindex="5" class="">

it just happens to that field do you have any idea why?

thank you so much!


Solution

  • The must be something diffrent that is wrong. Maybe your class? Please show us the CSS Code.

    Here is a working Code:

    function validateEmptyPass(pass) {
      var a = $('#password-conf');
      var error = "";
      var fieldName;
      if (a[0].value.length === 0) {
        a[0].className = "errorField"
        error = "password field empty"
      } else {
        a[0].className = '';
      }
      return error;
    }
    .errorField {
      background: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input id="password-conf" name="passwordConf" rel="Password Confirmation" placeholder="password confirmation" type="password" maxlength="25" tabindex="5" class="">
    
    <input type="button" onclick="validateEmptyPass()" value="validateEmptyPass()" />