0

我对一些 javascript 逻辑有点迷失了。我有一个包含 3 个文本字段的表单。它们通过 javascript(无占位符)显示默认值。当表单被聚焦时,值被清除,当表单被模糊时,如果字段值没有改变,则恢复默认值。

我必须编写一些条件逻辑来确保如果值发生更改,字段文本颜色从灰色(默认占位符值)更改为黑色。

这 3 个字段具有不同的默认值。我尝试在 Blur 上编写一个通用脚本来检查当前字段的值,以根据默认值对其进行测试。

  $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'))]);
    });
  });

但是我的测试总是返回 true,因为当我在 blur 上运行测试时,占位符值没有恢复。

处理这个问题的最佳方法是什么?

干杯

4

2 回答 2

1

使用 jQuery,你可以这样做:

假设以下 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;
}

小提琴:http: //jsfiddle.net/uWPJC/

于 2013-02-18T12:43:51.980 回答
0

尝试使用这段代码,你会得到你想要的

    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;
        }
于 2013-02-18T12:37:56.713 回答