How to change the CSS style on required form entries based on their values

advertisements

I would like to know how to write the javascript to alter the style of form elements which are required; and change them if they have values in them.

What I want to do is have a colored border around the required text fields when they are blank, and remove the border style when they have values.

what I've thought of doing is to write a single javascript function which checks if the value is empty and set the appropriate style:

function requiredElement(id) {
  var Input = document.getElementById(id);
  if(Input.value==null) {
    Input.style.border = '2px solid #FF0000';
  }
}

But what I'm stuck with is changing the style as user enters/removes characters in these required fields, and calling the function for the fields.

I have a simple html form, each input has a unique ID.


Use jQuery

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>

Then add this code:

$('.important').change(function() {
  if(($(this).val()) != '') $(this).css( 'border-width', '0' );
  else  $(this).css( 'border-width', '2' );
});

Assuming you added a border in the css

.important
{
    border-style:solid;
    border-width:2px;
    border-color:red;
}