我为我的练习创建了这个非常简单的代码。我试图测试jQuery的必填字段。但它没有用。有人可以告诉我为什么吗?此外,如果您还可以告诉我如何改进它,那将非常有用。我想通过在字段下面显示错误消息而不是警告框来使其更好,并且如果发生错误也将文本字段颜色更改为红色。
$(document).ready(function() {
$('.btn').click(function() {
if ($('#fn').val() == "" || $('#ln').val() == "") {
alert('Please complete the required field(s)');
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body style="background-color : black">
<br /><br /><br />
<div style="text-align:center; color:white;">
<form>
<strong>
First Name         <input id = "fn" type = "text" /> <br /><br />
Middle Name         <input id = "ln" type = "text" /> <br /><br />
Last Name         <input type = "text" /> <br /><br />
Gender         <select>
<option value = "Male">Male</option>
<option value = "Female">Female</option>
</select> <br /><br />
Married         <select>
<option value = "No">No</option>
<option value = "Yes">Yes</option>
</select> <br /><br />
Spouse Name         <input type = "text" /> <br /><br />
DOB         <input type = "date" /> <br /><br />
Email         <input type = "text" /> <br /><br />
Age         <input type = "text" /> <br /><br />
Mobile         <input type = "text" /> <br /><br /><br />
<button class="btn"> SUBMIT </button>
</strong>
</form>
</div>