In web development, forms are one of the important components of business logic, and form verification is a basic security consideration. In the form, the verification of the input box is the most basic and necessary, and judging whether the content of the input box is empty is the most common verification. Here we will introduce the method of javascript to realize real-time judgment that it is not empty.
<input type="text" id="input" oninput="checkEmpty()">
In the above code, the oninput event is added to the input. When the event is triggered, a function named checkEmpty will be called. This function is used to determine whether there is a value in the input.
function checkEmpty() { var inputEl = document.getElementById("input"); if (inputEl.value.trim() == "") { inputEl.style.borderColor = "red"; inputEl.nextElementSibling.innerHTML = "此项不能为空"; } else { inputEl.style.borderColor = "green"; inputEl.nextElementSibling.innerHTML = ""; } }
In the above code, we first obtain the DOM object of the input box, and then change the style or prompt information of the input box by determining whether the value of the input box is empty. When the input box is empty, we set the border color of the input box to red, and add the prompt message "This item cannot be empty" behind the input box; when the input box is not empty, set the border color to green , and clear the prompt information.
var inputs = document.getElementsByClassName("required"); for (var i = 0; i < inputs.length; i++) { inputs[i].addEventListener("input", checkEmpty); }
In the above code, we first use the document.getElementsByClassName("required") method to obtain all input boxes that need to be verified, and then use loop traversal to add oninput events for all input boxes, and the events are triggered The checkEmpty function is executed for verification.
Summary:
Through the above three steps, we can implement a simple, javascript-based verification that the input box is not empty in real time. Of course, you may encounter more complex form validation requirements in actual development. You may wish to use the above example as a basis and make appropriate improvements based on business logic.
The above is the detailed content of How to judge whether it is empty in real time with javascript. For more information, please follow other related articles on the PHP Chinese website!