Reputation: 77
I'm back with another jQuery problem, woo! Here's what I'm trying to do, I have text field, and I want it's background to turn red if the user doesn't input anything, or turn green if something is entered. Both checks occur on "blur," and I'm using ".animate()." to change the background color. (I have jQuery-Color to let me animate colors). Here is my script:
<head>
<script type="text/javascript" src="assets/javascript/jQuery.js"></script>
<script type="text/javascript" src="assets/javascript/jQuery-color.js"></script>
<script>
var jQ=jQuery.noConflict();
var fullNameValue=jQ(".fullName").attr("value");
jQ(document).ready(function(){
jQ(".fullName").blur(function(){
if(fullNameValue==null || fullNameValue==""){
jQ(".fullName").animate({
backgroundColor: "#AF383C",
color: "#FFFFFF"
});
}
else{
jQ(".fullName").animate({
backgroundColor: "#78BB6C",
color: "#000000"
});
}
});
});
</script>
</head>
Currently, on blur, the text field turns red, even if something is entered in the text field, which probably means something is wrong with my if statement, correct?
Upvotes: 0
Views: 1113
Reputation: 6500
function inputBorder() {
var i = $('input[type="text"]');
i.blur(function() {
i.removeClass('red green');
if(i.val() == "") {
i.addClass('red');
} else {
i.addClass('green');
}
});
}
$(document).ready(function() {
inputBorder();
});
Fiddle Here!
Upvotes: 1
Reputation: 413712
Your "fullNameValue" variable is established at a time when the <input>
field itself is not yet in the DOM. That statement should be inside your "blur" handler.
jQ(document).ready(function(){
jQ(".fullName").blur(function(){
var fullNameValue=jQ(".fullName").attr("value");
if(fullNameValue==null || fullNameValue==""){
jQ(".fullName").animate({
backgroundColor: "#AF383C",
color: "#FFFFFF"
});
}
else{
jQ(".fullName").animate({
backgroundColor: "#78BB6C",
color: "#000000"
});
}
});
});
What you're doing only makes sense if you check the value when the "blur" actually happens.
For further clarification:
var fullNameValue=jQ(".fullName").attr("value");
That statement sets "fullNameValue" to the value of the field. If the value later changes, the variable will not be updated; it remains a copy of the value at the time the statement was executed.
Finally, it's better to use .val()
to get the value of a form field:
var fullNameValue = jQ(".fullName").val();
Upvotes: 4