Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How javascript gets the form


May 29, 2021 Article blog


Table of contents


JavaScript's godcom is widely believed to be shared by everyone, starting with getting form data.

We used to do this when it was worth getting form forms:

<form action="" method="post">
<input type="text" name="name" id="name" value="aaa">
<input type="password" name="password" id="password">
<input type="submit" name="submit" value="提交" id="submit">
</form>
<script>
        var name1 = document.getElementById('name').value; //获取id为name的值
	var submit1 = document.getElementById('submit');//获取submit.准备为其绑定事件
	submit1.onclick = function(){alert(name1)}//为submit绑定点击事件,将name的值在也页面弹窗显示
</script>

This approach is not only cumbersome to get form values, but also a lot of code, so let's look at a faster and more introductory approach

First, get the value in input

<!--onsubmit事件是在提交表单时触发-->
<!-- return 一个函数:是指当函数的返回值位false时,表单不提交,为true时提交-->
<form action="" method="post" target="_blank" onsubmit="return mySubmit(this)">
<!--mySumit函数中的参数this是指form调用该函数时会将form传入函数中-->
		<input type="text" name="username" >
		<input type="submit" name="submit" >	
	</form>
	<script>
		function mySubmit(form){
		<!--定义formData对象-->
			let formData = new FormData(form);
			<!--利用fromData对象的get方法获取表单数据-->
			let username = formData.get('username');
			<!--进行一些判断或者操作-->
			if(username.length < 5){
				alert('用户名不得小于5位');
				return false;
			}else{
				return true;
			}
			return false;

		}
	</script>

Second, get the type type as a checkbox type input value

<form action="" method="post" onsubmit="return mySubmit(this)">
		<input type="checkbox" name="hoppy" value="music">音乐
		<input type="checkbox" name="hoppy" value="game">游戏
		<input type="checkbox" name="hoppy" value="movie">电影
		<input type="submit" name="" value="提交">
</form>
<script>
		function mySubmit(form){
			//定义formData对象
			let formData = new FormData(form);
			//获取值,因为get只能获取一个值,而这里是多选框,所以这里使用getAll方法
			let hoppy1 = formData.getAll('hoppy');
			console.log(hoppy1);
			//页面数据不进行提交,只是进行测试
			return false;
		}
</script>

Here's what the little editor has organized for you about how javascript gets the form.