views:

5257

answers:

2

Does anyone know how to reset the border color of an input control once you have modified it using javascript? Useful for validation by highlighting fields that have incorrect or invalid data in them etc.

E.g. changing the border:

document.getElementById('myinput').style.border = '1px solid red';

how to reset? the next line just removes the border completely...

document.getElementById('myinput').style.border = '';

if I reset the border color back to a particular color (e.g. black or grey etc), it may look strange in some browsers/operating systems that sort of 'theme' the controls...

thanks heaps!

+9  A: 

Don't do it with setting style attributes. Do it by using CSS classes. I would also recommend using a Javascript library to handle this. It just makes the code cleaner.

Removing CSS attributes is problematic because you don't always know what they should be set back to. Adding and removing classes just... works.

You can have multiple classes per element so there's really no argument against doing it this way (imho).

I'm used to jQuery so my example is with that.

Wrong way:

$("#myinput").css("border", "1px solid red");

Right way:

<style type="text/css">
.redborder { border: 1px solid red; }
</style>

<script type="text/javascript">
$("#myinput").addClass("redborder");
$("#myinput").removeClass("redborder");
$("#myinput").toggleClass("redborder");
</script>
cletus
A: 

Do you simply want the border to go away? I don't think so, as you have stated that is not the case.

The proper way to "reset" is to set to default. I am not sure what the default is, but I would guess something like '1px black' or similar.

I commonly use this technique in a variety of applications. When i do not know the default, I will set my own "default" so I can repeat it. One of my favorite techniques, with web pages, is to set the background color of the control, rather than the border. It is very visible and you can choose a more muted color and still have impact. In that case, it is very easy to set background back to white, which is the default.

Gregory A Beamer
I agree about using the background color. I'm using both actually, just I didn't have any problems clearing the background...
davidsleeps
I aim for an explicit approach. I set the form to default in a clearing routine and then bind with the "error" color. This is true with both background color and any other visual. Once I am confident of default, I may drop the clear() routine, depending on form complexity.
Gregory A Beamer