Rocket Rocket - 9 months ago 33
jQuery Question

JQuery Loop each Input for border color?

Is it possible to loop through each input and see if a specific border color exists ?

Currently I'm using a keyup event that triggers an ajax request to validate form input. That works well and if an error is noted the input has a style applied:

'border': '1pt solid #ff00ff', 'color': '#ff00ff'}

I also add an error message to a status DIV. What I need to do is clear the status but on when all errors have been addressed. As each error is cleared the color is removed from the border.

I have tried counting the errors and storing the count in localstorage, but if the user keeps entering a valid value in a field, the count is decreased which results in the status being cleared when it shouldn't be.

So can I check any input where the name starts with
and if any have the border color
then keep the status message otherwise remove the message from



As has been pointed out, this kind of thing is not usually done by setting borders and checking what borders are set. It's possible to do it that way, but it's cumbersome and error-prone.

A much easier way to manage element state (and "valid"/"invalid" is element state) would be to use CSS classes - especially if you want to modify the visual style of an element.

Here is what I would do. Add a CSS class "has-error" to your stylesheet.

/* by default, the error status is not shown */
.error-status {
  display: none;
  border: 1px solid red;

/* in a form that has an error, the error status is visible */
form.has-error .error-status {
  display: block;

Now, upon validation,

  1. Remove has-error from the <form> - just in case it had been set previously.
  2. Find all contained <input> elements you are interested in.
  3. Filter them down to those that are invalid (i.e. empty). For those that remain:
  4. Move back to the respective <form>.
  5. Add the has-error class.

This actually works for any number of forms and input elements. If there are no invalid input elements, the last two steps do nothing.

$("#btnVaidate").on("click", function() {
    .find("input[name^='name'], input[name^='cell'], input[name^='id']")
    .filter(function() { return !$.trim(this.value).length; })