2013-07-30 153 views
0

我对jquery有点新,所以请耐心等待。文字元素背景颜色变化

我正在开发注册系统并有密码并确认密码文本框。我希望设置确认框的背景颜色,只要两个框的内容发生变化。颜色将基于箱子内容是否匹配。

编辑 - 我原来的代码根本不改变背景颜色。我希望在用户输入时改变它,而不是焦点/模糊。

我的代码如下。

<input type="password" name="password" id="newpassword"/> 
<input type = "password" name = "confirm" id="confirm"/> 
<input type="submit" value="Register" id="Register"/> 

<script> 
    $(document).ready(function() { 
     $('#password').change(function() { 
      if ($('#newpassword').val().Equals($('#confirm').val())) { 
       $('#confirm').attr("backgroundcolor", "green"); 
       $('#Register').attr("disabled", ""); 
      } else { 
       $('#confirm').attr("backgroundcolor", "red"); 
       $('#Register').attr("disabled", "disabled"); 
      } 
     }); 
     $('#confirm').change(function() { 
      if ($('#newpassword').val().Equals($('#confirm').val())) { 
       $('#confirm').attr("backgroundcolor", "green"); 
       $('#Register').attr("disabled", ""); 
      } else { 
       $('#confirm').attr("backgroundcolor", "red"); 
       $('#Register').attr("disabled", "disabled"); 
      } 
     }) 
</script> 

在此先感谢

+0

而且?什么不起作用?错误信息 ? – Virus721

+0

你面临什么问题 –

+1

你在最后留下了'});'。 – Neal

回答

1
$(document).ready(function() { 
    $('#newpassword, #confirm').change(function() { 
     var $n = $('#newpassword'), 
      $c = $('#confirm'), 
      newp = $n.val(), 
      conf = $c.val(); 
     if (newp === conf) { 
      $c.css('background-color', 'green'); 
      $n.prop('disabled', false) 
     } else { 
      $c.css('background-color', 'red'); 
      $n.prop('disabled', true) 
     } 
    }); 
}); 

希望这是你想要做什么。

Fiddle

+0

谢谢你这是一个非常优雅的解决方案。但是你禁用了错误的元素。它应该禁用注册按钮。我已将更改功能更改为按键,这似乎更符合我的要求。 – DocSmiley

+0

@DocSmiley啊我现在看到它,不知道为什么我认为应该禁用newpassword – Spokey

2

使用CSS的方法,因为backgroundColor时不是属性。

$('#confirm').css("backgroundColor", "green"); 
+0

backgroundcolor不是CSS属性。 – Virus721

+0

这只是其中一个问题。 – Archer

+0

这是正确的..写backgroundColor(它也在jQuery工作) – Bernhard

1

试试这个代码http://jsfiddle.net/pQpYX/

$(document).ready(function() { 
    $('#confirm').keypress(function (event) { 
     if ($('#newpassword').val() == ($('#confirm').val() + String.fromCharCode(event.keyCode))) { 
      $('#confirm').css("background-color", "green"); 
      $('#newpassword').removeAttr("disabled"); 
     } else { 
      $('#confirm').css("background-color", "red"); 
      $('#newpassword').attr("disabled", "disabled"); 
     } 
    }); 
});