Instance code that checks if the value of a form element is empty

  • 2021-06-29 06:18:35
  • OfStack

1. Overview

In the actual development process, it is often necessary to determine whether the value of an element in a form submitted by the user is empty, and in one case, the value of all elements in the form is not allowed to be empty.This example shows a simple and effective way to determine if all elements in a form are empty.

2. Technical Essentials

This is mainly achieved in JavaScript by looping the elements attribute of the form object.The elements attribute of the form object is also an array of all elements of the form form on the page. For example, form.elements[0] represents the first element object of the form, and form.elements[n] represents the n element object of the form.

3. Specific implementation code

(1) Create a new index.jsp form page, which contains three elements that are not allowed to be empty and a submit button, and needs to define an id attribute value for one form, with the following key codes:


<form action="" id="myform">
<table align="center">
<tr>
<td> Speaker: </td>
<td>
<input type="text" name="messageUser" title=" Speaker "> 
</td>
</tr>
<tr>
<td> Message Title: </td>
<td>
<input type="text" name="messageTitle" title=" Title "> 
</td>
</tr>
<tr>
<td> Message content: </td>
<td>
<textarea rows="8" cols="45" title=" Message "></textarea>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="button" value=" carry   hand over " onclick="check()">
</td>
</tr>
</table>
</form> 

(2) on the page < script > 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 every 1 Are elements empty 
alert(myform.elements[i].title+" Can't be empty! ");
myform.elements[i].focus(); // Element gets focus 
return ;
}
}
myform.submit();
}

In JavaScript, the value attribute of the elements attribute of the form form object represents the value of the specified element.The name attribute represents the name of the specified form element;The title attribute represents the title of the form element.


Related articles: