In this article I will show you using jQuery how to check or validate any element or control exists in you (.html, .cshtml, .aspx , razor page or in you asp.net core mvc) page or not.
What is jQuery?
jQuery is a client side script. It is a library not a programming language same as JavaScript. jQuery comes with multiple ready to use feature like ajax, managing controls and many more. It very lightweight and easy to user.
How to check element or control exist using jQuery?
For validating first we need to add the jQuery library reference in your asp.net, .net core mvc or html or in you PHP application.
Download jQuery Library To download the jQuery library refer the download link.
Now you need to add the jQuery library reference in the header of your page as mentioned below. <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
After adding jQuery library reference you need to add the below mention html code or you Dom control in the body of the page. Below code represent a control in HTML file<html>
<head>
<title>jQuery Check If Element / Control Not Exists</title>
<script src="https://code.jquery.com/jquery-3.7.1.js"></script>
</head>
<body>
<input type="text" id="txtName"/>
<input type="buttton" value="Validate"/><br/>
<div id="divMessage"/>
</body>
</html>
Here is the code for your asp.net core mvc application. in this i have not added the button control you just need to replace the HTML control with mvc control.@Html.TextBoxFor(m => m.Name, new { @id="txtName" })
Or
@Html.TextBox("Name","", new { @id="txtName" })
Here is you script which will validate control exist in page or not.
var ValidateControl=function(){
var message="";
if ($("#txtName").length) {
message="You control exist";
}else{
message="Sorry control does not exist";
}
$("#divMessage").html(message);
}