<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<input class="input" name="input1" value="">
<input class="input" name="input2" value="">
<input class="input" name="input3" value="">
<input class="input" name="input4" value="">
<input class="input" name="input5" value="">
<input class="input" name="input6" value="">
</body>
<script>
(function(){
var inputs = document.getElementsByClassName('input'),
i = 0,
n
//给每个input绑定一个change事件,每个change事件再绑定一个submit方法
while (n = inputs[i]){
n.addEventListener('change', submit, false)
i++
}
//检查是否已经都输入了结构,都返回了后执行Ajax异步提交表单到'
function submit(){
var checkVal = checkValue()
if(!checkVal) return false
var xhr = new XMLHttpRequest(),
formData = new FormData() //H5form表单API
for(var i = 0 i < checkVal.length i++){
formData.append('input' + i, checkVal[i])
}
xhr.onload = function(){
//相应结果
var response = xhr.responseText
}
xhr.open('POST', 'http://localhost')
xhr.send(formData)
}
//判断搜索输入框是否都输入了值,没有就返回false,有就返回结果数组
function checkValue(){
var valArr = []
for(var i = 0 i < inputs.length i++){
var val = inputs[i].value
if(typeof val === 'string' && val != ''){
valArr.push(val)
}else{
return false
}
}
return valArr
}
}())
</script>
</html>
当表单submit的时候。要执行一段JS,可以在form里填写属性onsubmit<form method="post" action="" onsubmit="return dc()">
这样在form表单提交前会先执行dc这个函数;如果dc这个函数执行完返回true;则表单提交,返回false则取消表单提交