1. Overview
In actual development, it is often necessary to determine whether the value of an element in the form submitted by the user is empty. Another situation is that the values of all elements in the form are not allowed to be empty. This example will introduce a simple and effective way to determine whether all elements in a form are empty.
2. Technical points
It is mainly implemented in JavaScript by looping through the element attribute of the form object. The elements attribute of the form object is an array of all elements of the form form in the page. For example, form.elements[0] represents the first element object of the form, and form.elements[n] represents the nth element object of the form.
3. Specific implementation code
(1) Create a new index.jsp form page. The form of the page contains 3 elements that are not allowed to be empty and a submit button. You need to define the id attribute value of a form. The key code is as follows:
<form action="" id="myform"><table align="center"><tr><td>Message: </td><td><input type="text" name="messageUser"> </td></tr><tr><td>Message title: </td><td><input type="text" name="messageTitle"> </td></tr><tr><td>Message content: </td><td><textarea rows="8" cols="45"></textarea></td><tr><td align="center" colspan="2"><input type="button" value="Submit" onclick="check()"></td></tr></table></form>
(2) Write a method to verify that the value of the form element is not allowed to be empty in the <script> tag of this page. The key code is as follows:
function check(){var myform = document.getElementById("myform"); //Get form form object for(var i=0;i<myform.length;i++){ //Loop form form if(myform.elements[i].value==""){ //Judge whether each element is empty alert(myform.elements[i].title+"can't be empty!");myform.elements[i].focus(); //Elements get focus return ;}}myform.submit();}In JavaScript, the value attribute of the elements attribute of the form object represents the value of the specified element; the name attribute represents the name of the specified form element; and the title attribute represents the title of the form element.
The above is the relevant knowledge about the example code that the editor introduces to you to check whether the value of the form element is empty. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!