首页 > 解决方案 > 表单提交javascript html中的触发操作

问题描述

如果字段验证没有错误,我正在尝试验证表单中的字段并在用户单击提交按钮时拉出不同的 html 文件。

  1. 但是,验证器似乎不起作用。我希望事件名称和位置字段为字母数字字符和空格,但它似乎也采用其他值。
  2. onClick="self.location='successPage.html'"放在提交按钮内似乎也不会验证字段。如果表单中的所有字段都已成功验证,我希望它移动到 successPage.html 文件。

我不想使用 jQuery。

这是我的代码:

<form action="" >
		<p>
			<label>
			  Day of the week:<br>
				  <select name="days">
					<option value="mon">Monday</option>
					<option value="tue">Tuesday</option>
					<option value="wed">Wednesday</option>
					<option value="thu">Thursday</option>
					<option value="fri">Friday</option>
					</select><br>
			</label>
			<label>
			  Start Time:<br>
					<input id="appt1" type="time" name="appt1" min="9:00" max="18:00" required /><br>
			</label>
			<label>
			  End Time:<br>
					<input id="appt2" type="time" name="appt2" min="9:00" max="18:00" required /><br>
			</label>
			<label>
			  Event Name:<br>
					<input id="ename" type="text" name="ename"  required /><br>
			</label>
			<label>
			  Location:<br>
					<input id="loc" type="text" name="location" required /><br><!--pattern="[A-Za-z0-9\s]"-->
			</label>
			<label>
			  Enter URL for the pictture:<br>
					<input id="urlpic" type="text" name="urlname" />
			</label>
			<br><br>
			
			<input type="reset" id="reset" value="Reset" />
			<input type="submit" id="submit" value="Submit" /><!--onClick="self.location='successPage.html'"-->
			<!-- <input type=button value="Submit" onClick="self.location='successPage.html'"> -->
		</p>
		</form>
    <script>
		function chkName() {
			var myName = documnet.getElementById("ename");
			var pos = myName.value.search( /^[A-Za-z0-9\s]/);
			if (pos != 0) {
				alert("Please check your input (" + myName + ") again");
				return false;
			} else
				return true;
		}
		
		function chkLoc() {
			var myLoc = documnet.getElementById("loc");
			var pos = myLoc.value.search( /^[A-Za-z0-9\s]/);
			if (pos != 0) {
				alert("Please check your input (" + myLoc + ") again");
				return false;
			} else
				return true;
		}
		
		document.getElementById("ename").onchange = chkName;
		document.getElementById("loc").onchange = chkLoc;
		
		</script>

标签: javascripthtmlregexformsvalidation

解决方案


<form action="." method="POST" onsubmit="return validate(this)">
    <input type="submit" value="Submit">
</form>

form元素会在用户提交的时候传入到validate函数中,返回false表示不提交,返回true表示提交。

<script>
    function validate(form) {
        console.log(form); // log element to console on submit
        return false; // replace with true if input is good to be submitted
    }
</script>

推荐阅读