0

Using jquery, how can I change the color of these elements to red if the textboxes contain defaultvalues and the 'isrequired' value is "Yes"?

<input type="text" value="Name" isrequired="Yes">
<input type="text" value="Address" isrequired="No">
<input type="text" value="Age" isrequired="Yes">

2 Answers 2

4

Change your input html to add an extra data-* attribute which store defult value

<input type="text" value="Name" data-default="Name" isrequired="Yes">
<input type="text" value="Address" data-default="Address" isrequired="No">
<input type="text" value="Age" data-default="Age" isrequired="Yes">

Jquery

$('input[isrequired=Yes]').each(function(){
if($(this).val()==$(this).data("default"))
{$(this).css('color', 'red');}
})

Update : With using defaultvalue property which is very new to me

$('input[isrequired=Yes]').each(function(){
  if (this.value == this.defaultValue) {$(this).css('color', 'red'); }

});

Much better ,cleaner.

Sign up to request clarification or add additional context in comments.

4 Comments

do you mean if($(this).val()==$(this).data("data-default")) it worked when I changed "value" to "data-default"
Or if($(this).val()==$(this).attr("data-default"))
No extra attribute is required thanks to the defaultValue property. See my answer for an example.
Only this one worked: if($(this).val()==$(this).attr("data-default"))
1

The following will change the text field text red if the value is the default value as the user types.

JavaScript: (requires jQuery)

$('input[type=text][isrequired=Yes]').on("change", function(){
  if ($(this).val() == this.defaultValue) { $(this).addClass("req"); }
  else { $(this).removeClass("req"); }
});

CSS:

.req { color:red }

2 Comments

$(this).defaultValue is undefined so use this.defaultValue
@undefined: Ahh, habit. Fixed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.