jQuery 是一个快速、小巧且功能丰富的 JavaScript 库,它简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。jQuery 的价格验证通常是指使用 jQuery 来验证用户输入的价格是否符合特定的格式或范围。
100.00
。10.00
到 1000.00
。以下是一个使用 jQuery 进行价格验证的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Price Validation</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<form id="priceForm">
<label for="price">Price:</label>
<input type="text" id="price" name="price">
<button type="submit">Submit</button>
</form>
<div id="error-message" style="color: red;"></div>
<script>
$(document).ready(function() {
$('#priceForm').on('submit', function(event) {
event.preventDefault();
var price = $('#price').val();
var errorMessage = '';
// 格式验证
if (!/^\d+(\.\d{1,2})?$/.test(price)) {
errorMessage = 'Price must be in the format of 100.00';
}
// 范围验证
if (price && (parseFloat(price) < 10 || parseFloat(price) > 1000)) {
errorMessage = 'Price must be between 10.00 and 1000.00';
}
if (errorMessage) {
$('#error-message').text(errorMessage);
} else {
$('#error-message').text('');
// 提交表单
this.submit();
}
});
});
</script>
</body>
</html>
event.preventDefault()
阻止表单默认提交行为,并在验证通过后再手动提交表单。通过上述方法,可以有效地使用 jQuery 进行价格验证,确保用户输入的价格是有效的。
领取专属 10元无门槛券
手把手带您无忧上云