shaneburgess
shaneburgess

Reputation: 15882

Jquery Set individual input border color

Is it possible to set a color of a specific input field using jquery?

I would like to set a border to red if it fails some validations that I wrote and turn it back to black if it is fine.

Any way to do this?

Upvotes: 5

Views: 20064

Answers (3)

Sir Robert
Sir Robert

Reputation: 4946

The best way is to perform your validations and add a class to each element that didn't pass. That will keep a clean separation of form and content.

Assuming the following form:

<form id="myAwesomeForm">
    <input type="text" id="A" name="A"/>
    <input type="text" id="B" name="B"/>
    <input type="text" id="C" name="C"/>
</form>

You could add an "on-submit" handler that validates the data this way (assuming you've defined a function isFieldValid somewhere that determines validity):

;(function ($) {

  // When the document is ready... 
  $(document).ready(function () {
    // ... put a "submit" trigger on the form that checks data.
    $("#myAwesomeForm").submit(function () {

      // Make a list of the input fields we care about.
      var fieldList = ['A', 'B', 'C'];
      var areAllFieldsValid = true;

      // Loop through the inputs we care about
      for(var i = 0; i < fieldList.length; i++) {

        // Test for validity based on some function you defined somewhere.
        if (!isFieldValid("#A")) {
          // Mark this field as having invalid-data (and anything else
          // you want to do here).
          $("#A").addClass("invalid-data");
          // Make a note that we hit a false field so we can abort the submit.
          areAllFieldsValid = false;
        }
      }

      // Return true/false depending on whether we got invalid
      // data.  If this is false, the submit will be aborted.
      return areAllFieldsValid;
    });
  });

})(jQuery);

Then you just need to define a CSS class in your file:

/* My CSS file */
.invalid-data { border: 1px solid red; }

Upvotes: 1

mcgrailm
mcgrailm

Reputation: 17640

why do people always want to write there own code what do they think they are programmers ;^ ) you should consider validation plugin

I would do something like

  $('#item_id').addClass('errorClass');

that was you can add put it all in classes and swap as needed

Upvotes: 4

Aaron Saunders
Aaron Saunders

Reputation: 33345

in your validation code, set the field with the error

$('#afieldID').addClass("error");  

in your validation code, set the field with no error

$('#afieldID').removeClass("error");  

stylesheet code

.error {
    border: solid 2px #FF0000;  
}

Upvotes: 8

Related Questions