$(document).ready(function() {
//attach keypress event listener to the whole document
$(document).keypress(function(event){
if(event.keyCode === 13){
SearchThis.submit();
return false;
}
});
});
所以现在只要按下回车键就会提交我的表单(SearchThis),这很好但是如何修改它以检查mysearchfied在提交之前是否已完成?
IE。如果mysearchfied为空且按下回车键,则不提交表单。如果mysearchfied包含文本并按下回车键,则提交表单。
希望你能帮忙!感谢...
答案 0 :(得分:1)
如果您只想验证文本框是否符合要求,请使用HTML5 required attribute
,如:
<input type="text" class="form-control" name="mysearchfield"
value="" id="mysearchfield" placeholder="Company or SmartPages Category..." autocomplete="off" required>
答案 1 :(得分:0)
if (event.keyCode === 13) {
if ($('mysearchfied_ID_or_Class').val()!=='') {
//mysearchfied is not empty
SearchThis.submit();
}
else {
//dont submit, do your checks
}
return false;
}
答案 2 :(得分:0)
验证表单有两种方法。
- &GT;检查是有效的表单有效函数
SearchThis.validate().valid()
- &GT;按照@ n01ze
的说明验证每个字段的值答案 3 :(得分:0)
如果输入字段的id是mysearchfield,那么你可以这样做:
var msf = document.getElementById("mysearchfield").value;
$(document).ready(function() {
//attach keypress event listener to the whole document
$(document).keypress(function(event){
if(event.keyCode == 13){
if (msf != "") {
SearchThis.submit();
return false;
}
else
{
// some code here....
}
}
});
});
答案 4 :(得分:0)
listenOn = function(domElement) {
domElement.addEventListener('keydown', function(event) {
if (event.keyCode == 13) {
onEnterPressed();
}
});
function onEnterPressed() {
if (validateForm()) {
submitForm();
} else {
alert('Invalid form');
}
}
function validateForm() {
var inputValue = document.getElementById("myInput").value;
return (inputValue.length >= 1);
}
function submitForm() {
var formElement = document.getElementById("myForm");
alert('Submit form');
formElement.submit();
}
}
listenOn(document);
//listenOn(document.getElementById("myForm")); //You could also listen keydowns on form element(sure only if global keypress isn't exactly what you want).
<form id="myForm" action="#send.php">
<input id="myInput" type="text" placeholder="I'm empty now." />
</form>