0

I'm quite surprised that I wasn't able to find anything related to this on Google.

The issue I have now is I want my form fields to highlight based on their validity, but ONLY after the user has interacted with the form. I don't want invalid fields to be red as soon as the page is loaded. I tried using the :visited and :focus-within with my form element, but the former doesn't work and latter doesn't do what I want.

Am I not asking this question the right way?

Edit: I did come across onblur in my search but I thought there would be an intuitive way to do this with CSS only, turns out I was wrong → Does CSS have a :blur selector (pseudo-class)?

asa9ohan
  • 167
  • 5
  • To do this you will need to use javascript and hook into the onFocus/onBlur event of an input field – Richard Hpa May 26 '21 at 02:28
  • You need to use the onblur event to detect that a focused element has lost focus. – Dan Mullin May 26 '21 at 02:30
  • 1
    Does this answer your question? [Generic way to detect if html form is edited](https://stackoverflow.com/questions/959670/generic-way-to-detect-if-html-form-is-edited) – Chris W. May 26 '21 at 02:36
  • Interesting things come up when you paste the question title into google ;) – Chris W. May 26 '21 at 02:37

3 Answers3

1

just check when the users starts typing with the onkeydown event


<input type="text" onkeydown="myFunction()">

0

You will need an onchange event listener on your inputs. As soon as the input loses focus, the javascript function will fire. I provided you with a code snippet as an example.

You can also look for other inputs like onblur or onkeypress but onchange is more versatile as it will work also for select tags.

If you want to know more on DOM events, you can see the w3schools documentation.

const validateInput = (e) => {
  if (e.value.length < 9) {
    e.classList.toggle("error")
  }
}
.error {
  border: 2px solid crimson;
}
<input type="text" placeholder="enter your username" onchange="validateInput(this)" />
pensum
  • 980
  • 1
  • 11
  • 25
0

There are a couple ways you can go about it:

You can use Jquery:

$('#YourElementID').on('change keypress paste textInput input', function (){
   console.log("Something has changed");
}

Achieving this natively with Javascript has alluded me for a while:

document.getElementById("YourElementID").onkeydown = function () {
   console.log("Something has changed");
}

To bind it to a function in a Javascript class you can use the normal Bind(this) syntax:

#Start() {
    this.htmlDOM.onkeydown = this.OnInput.bind(this);
}

OnInput() {
    if (this.previousValue != this.jqueryObject.val()) {
        console.log("Value has changed");
    } else {
        console.log("Value has not changed");
    }
    this.previousValue = this.jqueryObject.val();
}
Tiaan
  • 698
  • 2
  • 10
  • 32