Skip to content Skip to sidebar Skip to footer

How To Change The Css Style On Required Form Inputs Based On Their Values

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 co

Solution 1:

Use jQuery

<scriptsrc="//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;
}

Solution 2:

To determine when the element's value changes, bind your custom function to the onchange and onkeypress events (or, in jQuery, bind to .change() and .keypress()).

To actually change the appearance of the element, It's best to define styles in a CSS class and use JavaScript to add/remove the class as appropriate.

You can change an HTML element's CSS classes through JavaScript like this:

element = document.getElementById("myElement");element.className = "invalid";

Or, in jQuery, use the .addClass() function:

$("#myElement").addClass("invalid");

HTML:

<inputid="something" name="something"type="text"class="inputClass"
    onchange="requireElement(this)"
    onkeypress="requireElement(this)" />

JavaScript:

functionrequireElement(element) {
    if(element.value == null)
        element.className = "inputClass invalid";
    else
        element.className = "inputClass";
} 

Post a Comment for "How To Change The Css Style On Required Form Inputs Based On Their Values"