开发者

Is it possible to apply styles to the value of a form field?

I have a form input tag with some text assigned to its value attribute:

<input type="text" name="firstName" value="First Name*" />

Since this is a required field, 开发者_JAVA百科how do I style the asterisk at the end of the "First Name*" string to be the color red? Is this even possible?... How do you style the values of pre-populated form fields?

Thank you.


I think you're making this more complicated then it should. There may be a way using javascript or jquery but I think that's overkill.

I would just put it on the outside of the box and style it within a <span> tag.


I don't think you can style one character to be red but you could style the whole string to be red.

What I would probably do is set the asterisk outside the input box and style it like this

<input ...value="FirstName"><span style="color: #FF0000;">*</span>


No, it's impossible. You'd have to fake it.

However, that's what <label>s are for!!

<label>First Name* <input name=firstName required></label>


Even if it would be possible, it'd not be a good practice. Data should always be separated from the representation. You don't want anything else but the data that you really need to be posted.

It'd be a good idea to go with the jQuery solution that simply assigns a class to the input field on post if there's an error, e.g. makes the text inside the input red, draws the red border around the input box etc.


If you're using asp .net why not just use the required field validator control and let it do the work for you.


Instead of adding * to the field, I would suggest signifying the required field by modifying the element's styling through CSS and jQuery/JavaScript.

Working example: http://jsfiddle.net/wstGQ/

CSS:

input {
 color: #ccc;   
}
.required {
 color: #FF0000;
 border: 1px solid #FF0000;   
}

jQuery:

$('input').focus(function(){
    var obj= $(this);
    var oldVal = obj.val();

    obj.blur(function(){
        if(obj.val() == oldVal){
         obj.val('Please enter a valid option').addClass('required'); 
        }else{
         obj.removeClass('required');   
        }
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜