我有一个使用ajax发布表单值的表单,似乎它没有读取表单输入上的required
属性。有谁能告诉我出了什么问题?
代码:
<script>
$(function () {
$("#send-email").click(function () {
var subject = $("#subject").val();
var name = $("#name").val();
var email = $("#email").val();
var phone = $("#phone").val();
var message = $("#message").val();
var nationality = document.getElementById("nationality");
var selNationality = nationality.options[nationality.selectedIndex].text;
//
$.post("mail.php", {"subject": subject, "name": name, "email": email, "phone": phone, "nationality": selNationality, "message": message, }, function () {
console.log(subject);
console.log(name);
console.log(email);
console.log(phone);
console.log(selNationality);
console.log(message);
alert("Thanks for contacting us, we will be back to you as soon as possible!");
});
});
});
</script>
<form action="mail.php" method="POST">
<div class="form-row">
<p>Subject</p>
<input type="text" id="subject" name="subject" required>
</select>
</div>
<div class="form-row">
<p>Name</p>
<input type="text" id="name" name="name" required>
</div>
<div class="form-row">
<p>Nationality</p>
<select name="nationality" id="nationality" required>
<option value="">Select Nationality</option>
</select>
</div>
<div class="form-row">
<p>Contact number</p>
<input type="text" id="phone" name="phone">
</div>
<div class="form-row">
<p>Email</p>
<input type="text" id="email" name="email" required>
</div>
<div class="form-row">
<p>Message</p>
<textarea style="width:590px;height:100px;" id="message" name="message" cols="80" rows="12" required></textarea>
</div>
<div class="form-row">
</div>
<div class="form-row">
<input type="submit" onclick="return false;" id="send-email" value="SEND" name="send"/>
</div>
</form>
答案 0 :(得分:0)
这里有几件事情错了。解决方案取决于您的需求。
1)如果您不需要对mail.php
进行异步调用,只需删除javascript内容即可。执行此操作时:<form action="mail.php" method="POST">
所有表单输入都将使用POST发送到所选操作,因此您不需要使用javascript。
2)如果你确实需要加载mail.php
asynk,你需要做几件事才能工作:
<form>
onclick="return false;"
检查数据是否完成,f.ex。:
var complete = true;
if(subject==""||name==""||email=="") {
complete = false;
}
if(complete) {
//send post to mail.php
} else {
alert("You need to fill in all the fields");
}
请注意,并非所有资源管理器都支持此功能:http://www.w3schools.com/tags/att_input_required.asp