1

I'm learning some Javascript, which I'm incorporating into another project. I have some input fields with maxlength set at 20. They currently have a border set to them via CSS:

.textInput:focus {
    border: 2px solid green;
}

I'd like for the border of the input fields to go red when the user hits the maxlength limit - this part I've achieved:

$("#newsTitle").keypress(function() {
if($(this).val().length == 20) {
    document.getElementById('newsTitle').style.borderColor = "red";
   }
});

However, if the user is to delete some text, or backspace, I'd like the border to go BACK to green. Could someone give me some pointers on how to do this?

If theres a more efficient way to achieve what I have so far, do tell me. I feel my approach is a bit bulky and that theres no need to give the element ID twice if its within an if statement, which applies to the element ID in question.

Cheers,

Jack

3 Answers 3

3

I would actually do it like this:

$(function() {
  $("#newsTitle").keydown(function() {
      $(this).toggleClass('invalid', $(this).val().length >= 20);
  });
});
.textInput:focus {
  border: 2px solid green;
}

.textInput.invalid,
.textInput.invalid:focus {
  border: 2px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="textInput" id="newsTitle">

Sign up to request clarification or add additional context in comments.

1 Comment

I really like this answer thank you. I like how the script actually triggers the different CSS depending on the value. Much appreciated!
1

$("#newsTitle").keypress(function() {
  if($(this).val().length == 20) {
      $(this)[0].style.borderColor = "red";    
  } else {
      $(this)[0].style.borderColor = "green";
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id="newsTitle">

Comments

1

You can try this code

$("#newsTitle").keypress(function() {

  if($(this).val().length >= 20) {
   $(this).removeClass("valid");
      $(this).addClass("invalid");  
  } else {
    $(this).addClass("valid");
    $(this).removeClass("invalid");
  }
});
.invalid {
   border: 2px solid red;
}

.valid {
   border: 2px solid green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type='text' id="newsTitle">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.