For ASP.NET WebForms:
Load jQuery from a CDN:
Consider loading jQuery from a Content Delivery Network (CDN) like Google or Microsoft to improve loading speed and reduce the load on your server.
html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Use the $ Symbol Safely:
In ASP.NET WebForms, the $ symbol is used by both jQuery and ASP.NET AJAX. If you are using jQuery alongside ASP.NET AJAX, use jQuery.noConflict() to avoid conflicts.
javascript
var $j = jQuery.noConflict();
$j(document).ready(function() {
// Your jQuery code using $j instead of $
});
UpdatePanel Considerations:
When working with ASP.NET UpdatePanels, be cautious about how jQuery events are bound. Use pageLoad() function to ensure jQuery events are re-bound after an UpdatePanel update.
javascript
function pageLoad(sender, args) {
// Your jQuery code here will be re-bound after UpdatePanel update
}
For ASP.NET MVC and ASP.NET Core:
Use Unobtrusive JavaScript:
Leverage unobtrusive JavaScript techniques, especially in ASP.NET MVC and ASP.NET Core. Keep your JavaScript separate from your HTML and use data attributes to attach behaviors.
Ajax Requests:
Use jQuery's AJAX functions ($.ajax(), $.get(), $.post()) for making asynchronous requests. In ASP.NET Core, you can also use the built-in $.ajax() function with Razor Pages.
Bundle and Minify JavaScript:
Bundle and minify your JavaScript files to reduce the number of HTTP requests and improve performance. ASP.NET MVC and ASP.NET Core provide bundling and minification features.
Client-Side Validation:
Utilize jQuery for client-side form validation. You can customize validation messages and rules easily using jQuery.
AJAX Helpers:
In ASP.NET MVC, consider using Ajax.BeginForm and related AJAX helpers. They integrate well with jQuery and make it easier to handle AJAX requests and updates.
Partial Views and jQuery:
When using Partial Views, make sure to rebind your jQuery events after loading a Partial View via AJAX. Use event delegation to handle events for dynamically loaded content.
javascript
$(document).on('click', '.your-button-class', function() {
// Your code here
});
Error Handling:
Implement proper error handling in your AJAX requests. Use jQuery's error callback to handle errors gracefully and provide meaningful error messages to users.
Use CDN for jQuery:
Similar to WebForms, if you are not bundling jQuery, consider using a CDN link to load jQuery. This can improve loading times and reduce the load on your server.
html
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
Lazy Loading:
Consider lazy-loading jQuery plugins or libraries that are not immediately necessary for the page load. Load them only when the user interacts with specific features requiring those plugins.
Upgrade to the Latest Version:
Always use the latest stable version of jQuery to benefit from improvements, bug fixes, and security enhancements.
Remember, while jQuery is a powerful tool, evaluate whether you really need it, especially in modern applications where vanilla JavaScript or modern JavaScript frameworks like React, Angular, or Vue.js might be more appropriate choices depending on the complexity of your project. Always aim for optimized, efficient, and maintainable code.
To load messages in the popup we can use below command
$(#GetMsg).html("Your custom message");
Some time below command is not working to dispaly message so we need to use.html() only.
$("GetMsg").val("You custom message");
$('#txtContact').on('keypress', function (e) {
const key = String.fromCharCode(e.which);
const allowedChars = /[\d\(\)\-\s]/; // Only allow digits, parentheses, hyphen, and spaces
// Prevent input if it doesn't match the allowed characters
if (!allowedChars.test(key)) {
e.preventDefault();
}
});
$('#txtContact').on('input', function () {
// Limit the format to (XXX) XXX-XXXX as the user types
let inputVal = $(this).val();
// Remove any disallowed characters and restrict format to (XXX) XXX-XXXX
inputVal = inputVal.replace(/[^\d\(\)\-\s]/g, '');
// Apply format restrictions
if (inputVal.length > 14) {
inputVal = inputVal.slice(0, 14);
}
// Enforce the correct pattern at each stage
const formatted = inputVal
.replace(/^(\d{3})$/, '($1) ') // (XXX
.replace(/^\((\d{3})\)\s(\d{3})$/, '($1) $2-') // (XXX) XXX-
.replace(/^(\(\d{3}\)\s\d{3}-\d{4}).*/, '$1'); // Final format
$(this).val(formatted);
});
$('#txtContact').on('blur', function () {
// Validate the full format on blur
const isValid = /^\(\d{3}\) \d{3}-\d{4}$/.test($(this).val());
if (!isValid) {
$("#Id").attr("successFlag", "0");
$('#Id').html("Phone number format should be (XXX) XXX-XXXX");
$('#Id').modal();
$(this).val(''); // Clear input if invalid
}
});
$('#txtZip').on('keypress', function (e) {
const key = String.fromCharCode(e.which);
const allowedChars = /[\d\-]/; // Only allow digits and hyphen
// Prevent input if it doesn't match the allowed characters
if (!allowedChars.test(key)) {
e.preventDefault();
}
});
$('#txtZip').on('input', function () {
// Remove any disallowed characters and enforce single hyphen use
let inputVal = $(this).val();
// Remove characters other than digits and hyphen
inputVal = inputVal.replace(/[^\d\-]/g, '');
// Ensure only one hyphen is allowed
const hyphenIndex = inputVal.indexOf('-');
if (hyphenIndex !== -1) {
// Allow only digits after the hyphen and prevent multiple hyphens
inputVal = inputVal.slice(0, hyphenIndex + 1) + inputVal.slice(hyphenIndex + 1).replace(/-/g, '');
}
$(this).val(inputVal);
});
$('#txtZip').on('blur', function () {
// Optional: Final validation for formats like "12345" or "12345-6789"
const isValid = /^\d{5}(-\d{4})?$/.test($(this).val());
if (!isValid) {
$("#Id").attr("successFlag", "0");
$('#Id').html('ZIP code format should be either "12345" or "12345-6789"');
$('#Id').modal();
$(this).val(''); // Clear input if invalid
}
});
$('#txtOrderNumber').on('keypress', function (e) {
const key = String.fromCharCode(e.which);
const allowedChars = /[a-zA-Z0-9,\s]/; // Allow only letters, numbers, commas, and spaces
// Prevent input if it doesn't match allowed characters
if (!allowedChars.test(key)) {
e.preventDefault();
}
});
$('#txtOrderNumber').on('input', function () {
// Remove any disallowed characters that might have been pasted
let inputVal = $(this).val();
inputVal = inputVal.replace(/[^a-zA-Z0-9,\s]/g, ''); // Remove anything that isn't allowed
$(this).val(inputVal);
});
$('#txtOrderNumber').on('blur', function () {
// Optional: Additional validation or formatting can go here if needed
const isValid = /^[a-zA-Z0-9,\s]*$/.test($(this).val());
if (!isValid) {
$("#Id").attr("successFlag", "0");
$('#Id').html('Order number should only contain letters, numbers, commas, and spaces.');
$('#Id').modal();
$(this).val(''); // Clear input if invalid
}
});