---
title: "在PHP和JS下，checkbox框的值该如何正确获取？"
author: "muyu"
date: "2009-06-12T16:42:12Z"
tags: []
categories: ["Web前端"]
slug: "php-js-checkbox"
draft: false
lastmod: "2009-06-19T18:22:47Z"
id: 407423
url: "https://muyu.iteye.com/blog/407423"
---

先看代码：

```
<?php
if ($_POST) {
	var_dump($_POST);
}
?>
<html>
<head>
</head>
<body>
<form id="myform" action='' method='post' name='Users_form' > 
<input type="checkbox" id="accept" name="accept" value="1"/><label for="accept">这是一个复选框</label>
<br>
<input type="button" name="js_btn" value="查看JS下的值" onclick="foo();">
<input type="submit" name="php_btn" value="查看PHP下的值">
</form>
</body>
</html>
<script>
  function foo(){
    var obj = document.getElementById('accept');
    if(obj.checked) {
      alert(obj.value);
    } else {
      alert('未选中');
    }
  }
</script>
```

 

 

在PHP，当用户选中复选框，$\_POST才能获取到它的值；当用户未选中的时候，$\_POST将没有 $\_POST\['accept']。

 

在JS，无论用户是否选中，document.getElementById('accept').value将始终返回value里的值。把属性checked作为复选框是否选中的条件，才能准确地获取。

 

**强调**

 

请尽量保持input的id和name成对出现，PHP获取post的键是根据name的，而js依赖id更方便一些。

 

单选的input同上。

 

**相关链接**：《[select、input-checkbox标签的多值处理](/blog/400464 "select、input-checkbox标签的多值处理")》