【发布时间】:2014-07-03 07:12:19
【问题描述】:
我在 CodeCademy 上做了一个项目系列,我在该系列中找到了一个使用 JavaScript/jQuery 进行客户端表单验证的项目。
我的 HTML 是:
<!DOCTYPE html>
<html>
<head>
<title>Form Validation</title>
<link rel='stylesheet' href='stylesheet.css' type='text/css'/>
<script type='text/javascript' src='script.js'></script>
</head>
<body>
<form>
First Name : <input type='text' id='fname' placeholder='Enter First Name'><br><br>
Last Name : <input type='text' id='lname' placeholder='Enter Last Name'><br><br>
Age : <input type='text' id='age' placeholder='Age'><br><br>
Sex : <input type='radio' class='sex'> Male <input type='radio' class='sex'> Female
</form>
<button id='submit'>Submit</button>
</body>
</html>
我的 JavaScript/jQuery 是:
$(document).ready(function()
{
var fname = document.getElementById('fname').val();
var lname = document.getElementById('lname').val();
var age = document.getElementById('age').val();
/*Do not know how to get element by class and that too, two different type. Have to check if user chose anything or not*/
$("#submit").click(function()
{
if(fname.length === 0)
{
alert("Please input a first name");
}
else if(lname.length === 0)
{
alert("Please input a last name");
}
else if(age.length === 0)
{
alert("Please input an age");
}
});
});
我不需要非常复杂的代码,如果那里有问题或需要添加一些内容,请在 HTML 部门帮助我。
另外,我不知道如何在一个类中获取不同的元素。我已经在我的 jQuery 中对此发表了评论,所以如果可以,请提供帮助。
这是 CodeCademy 项目中的一个问题,也是很多 JS 和 jQuery 新手遇到问题的地方,所以如果你能提供帮助,它将帮助很多人,而不仅仅是我。
谢谢!
【问题讨论】:
标签: javascript jquery html css web