Yannick Schall
Yannick Schall

Reputation: 34999

Change form field color if the value has change

I'm gettig a bit lost with some javascript logic. I have a form with 3 text fields. They show a default value through a javascript (no placeholder). When the form is focused, the value is cleared and when the form is blurred, the default value is restored if the field value hasn't been change.

I have to write some conditional logic to ensure that the field text color is changed from grey (default placeholder value) to black if the value is changed.

The 3 fields have a different default value. I tried to write a general script on Blur to check the value of the current field to test it against the default value.

  $fields = $('#webform-component-group-1 .webform-component-watermarked');
  var keys = [];
  var values = [];
  console.log($fields.length);
  $fields.each(function(){
    keys.push($(this).attr('id'));
    values.push($(this).val());
    $(this).blur(function(){
      console.log($(this).val());
      console.log($(this).val() !== values[keys.indexOf($(this).attr('id'))]);
    });
  });

but my test always return true as the placeholder value is not restored when I run the test on blur.

What would be the best way to handle this problem?

Cheers

Upvotes: 0

Views: 407

Answers (2)

Tom Pietrosanti
Tom Pietrosanti

Reputation: 4294

Using jQuery, you could do it like this:

Assuming the following HTML

<div id='fields'>
    <input value='start1' class='placeholder' />
    <input value='start2' class='placeholder' />
</div>

JavaScript

$('#fields input').each(function(){
    // Save initial placeholder values
    $(this).data('placeholder', $(this).val());
}).on("focus", function(){
    // Remove placeholder value and color on focus
    if( $(this).val() === $(this).data('placeholder') ){
        $(this).val('').removeClass('placeholder');
    }
}).on("blur", function(){
    // Restore placeholder on blur if input is empty
    if( $(this).val().length === 0 ){
        $(this).val($(this).data('placeholder')).addClass('placeholder');
    }
});

CSS

input.placeholder{
    color:#ccc;
}

input{
    color:#000;
}

Fiddle: http://jsfiddle.net/uWPJC/

Upvotes: 1

EnterJQ
EnterJQ

Reputation: 1014

Try to play with this code , you will get what u looking for

    var pass1 = document.getElementById('password');
    var pass2 = document.getElementById('vpass');
    var message = document.getElementById('confirmMessage');
    var goodColor = "#66cc66";
    var badColor = "#ff6666";
        if(pass1.value == pass2.value){
               pass2.style.backgroundColor = goodColor;
        }
        else{
               pass2.style.backgroundColor = badColor;
        }

Upvotes: 0

Related Questions