views:

38

answers:

5

I have a form that is validated by js when the user submits it. My code detects empty and invalid fields (ex 1 number in phone number is obviously an invalid phone number).

I am asked if i could highlight fields missing or in error. I think this would be cool IF i can do it automatically. With HTML like the below how can i make name, phone or whatever else turn red? i cant think of any solution. Maybe i can pull the html body from form find the target input and insert a div on the left side of the input to the prev tag and use that div to make the font red. But i HATE that idea because that requires poking the HTML instead of DOM and i am pretty sure some nastiness will occur. Any ideas?

Name: <input type=text name="Name"/>
Phone: <input type=text name="PhoneNo"/>
+1  A: 

You should rather write your HTML to have an element around the labels in the first place. The correct HTML would be

<label for="Name">Name:</label> <input type="text" name="Name" id="Name" />

Then just add a class to the label to turn it red when it should.

By the way, this even makes the input receive focus when the label is clicked! Yay!

Matti Virkkunen
+1  A: 

such as:

//some javascript validation here
name.style.color = 'red';
phoneNo.style.color = 'red';

?

Alex B
This won't quite work if the field is empty.
Matti Virkkunen
well you wouldn't have any text to make red then.
Alex B
@Alex B: Maybe the "Name:" or "Phone:" bit?
Robert
I'll +1 for the idea. If the verification is wrong i can make the field red as well (or just the field and not label). But yeah this wont work for the text beside inpuit if its empty (my main question) +1
acidzombie24
A: 

(1) Pull the form
(2) Loop through the inputs
(3) Find the one that needs attention
(4) Add the class .needsattn
(5) Add .needsattn { background:red;} to your CSS

Rudu
A: 

How about labels with the for attribute? - Check out its documentation here

Floyd Pink
+2  A: 

Change your HTML to have the <label> surrounding the 'Name' and 'Phone', which will make it more accessible and provide the functionality you're looking for.

HTML

<label for='Name'>Name:</label> <input type=text name="Name"/>
<label for='PhoneNo'>Phone:</label> <input type=text name="PhoneNo"/>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

jQuery

​$('input').blur(function() {
    $('label[for="'+$(this).attr('name')+'"]').css('color','red');
});​​​​

Live Example

http://jsfiddle.net/tve8J/

You'll of course have to add your validation, I don't know what you consider and 'invalid field'

Robert
bonus mention to Matti Virkkunen answer http://stackoverflow.com/questions/3731374/highlight-text-between-form-inputs/3731395#3731395
acidzombie24