Search code examples
javascriptjqueryformsonblur

Using onblur event for mutiple form fields


I have a simple function that applies formatting to a form field using an onblur event - if 7 characters have been input into the field, the field's border turns green. Fewer than 7 character results in a red border. I'd like to be able to apply the function to each form field individually as the user tabs through. Currently, if I fill in the first form field, both form fields are formatted at the same time. I think the answer is using a for loop that iterates through the inputs, I just don't know how to update my code to reflect that; any help is much appreciated.

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

<script>
function charCount() {
var char = document.getElementById("numb").value.toString().length
if (char == 7) {
    $("input").addClass("green").removeClass("red");
} else {
 $("input").addClass("red").removeClass("green");
 }
}
</script>

<style>
.green {border-color:#009900;}
.red {border-color:#990000;}
</style>
</head>

<body>
<p>Please input ID numbers:</p>
<input id="numb" maxlength = 7 onblur="charCount()">
<input id="numb" maxlength = 7 onblur="charCount()">

</body>
</html> 

Solution

  • 1.- You cannot have the same id for multiple inputs. Use a class instead.

    2.- Then use "this" to have a reference of the input that is being used Here's a working solution. Hope it helps!

     $(".numb").blur(function(){
            var char = $(this).val().length;
            if (char == 7) {
                $(this).addClass("green").removeClass("red");
            } else {
                $(this).addClass("red").removeClass("green");
            }
        });
    .green {border-color:#009900;}
    .red {border-color:#990000;}
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <p>Please input ID numbers:</p>
    <input class="numb" maxlength = 7>
    <input class="numb" maxlength = 7>