tags:

views:

28

answers:

3

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?

+1  A: 

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;  
}
Aaron Saunders
+1  A: 

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

mcgrailm
Thanks that helped. I don't want to use the validation plugin because my validations are pretty wacky and it would be much easier to write my own rather than to try to figure out how to get the validation plug in to do what I need.
dweebsonduty
A: 

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; }
Sir Robert