Home >Web Front-end >Front-end Q&A >How to determine whether form element exists in jquery
Judgment steps: 1. Use the jQuery selector to select the form element. The syntax "$("form")" or "$("#id attribute value")" will return a jQuery object containing the form element. ; 2. Use the length attribute to determine whether the jQuery object is empty. The syntax is "jQuery object.length!=0". If the return value is true, the form element exists. If the return value is false, the form element does not exist.
The operating environment of this tutorial: windows7 system, jquery3.6.1 version, Dell G3 computer.
In jquery, you can use the jQuery selector and length attribute to determine whether the form element exists.
Implementation steps:
Step 1. Use the jQuery selector to select the form element
1) The jQuery element selector is based on Element name selects the element.
$("标签名")
For example, $("form")
is to select the <form></form>
tag element.
2) The jQuery id selector selects elements based on the id attribute.
$("#id属性值") <form id="属性值"> //表单元素 </form>
will return a jQuery object containing the form element.
Step 2. Use the length attribute to determine whether the jQuery object is empty.
The length attribute can get the length of the jQuery object; then you can check whether the length is 0, that is Can determine whether the object is empty.
jQuery对象.length!=0
If it is not empty (the return value is true), the form element exists
If it is empty (the return value is false), Then the form element does not exist
Implementation example: Determine whether the form element label and input element label exist
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <script src="js/jquery-3.6.1.min.js"></script> <script type="text/javascript"> $(document).ready(function() { $("button").click(function() { var len1=$("form").length; var len2=$("input").length; if(len1!=0){ console.log("form元素存在") }else{ console.log("form元素不存在") } if(len2!=0){ console.log("input元素存在") }else{ console.log("input元素不存在") } }); }); </script> </head> <body> <form action="demo-form.php"> E-mail: <input type="email" name="userid"><br><br> <textarea></textarea><br><br> </form> <button>检查form元素和input元素是否存在</button> </body> </html>
As you can see, in the above example, both the form element and the input element exist.
[Recommended learning: jQuery video tutorial, web front-end video]
The above is the detailed content of How to determine whether form element exists in jquery. For more information, please follow other related articles on the PHP Chinese website!