Home  >  Article  >  Web Front-end  >  Implement checkbox checkbox example code based on javascript_javascript skills

Implement checkbox checkbox example code based on javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:17:191426browse

The example in this article explains the detailed code for implementing the checkbox in JavaScript and shares it with you for your reference. The specific content is as follows

Rendering:

Specific code:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
<script type="text/javascript">
function select_all(obj)
{
  //取得由所有hobby构成的一个数组对象
  //如果表单中,存在多个同名的name,将产生一个数组
  var arr = document.form1.hobby;
  if(obj.checked)
  {
    //为true执行代码
    for(var i=0;i<arr.length;i++)
    {
      arr[i].checked = true;
    }
  }else
  {
    //为false执行代码
    for(var i=0;i<arr.length;i++)
    {
      arr[i].checked = false;
    }
  }
}
function select_no_all()
{
  //取得所有的hobby对象
  var arr = document.form1.hobby;
  for(var i=0;i<arr.length;i++)
  {
    if(arr[i].checked)
    {
      //如果选中,则取消
      arr[i].checked = false;
    }else
    {
      //如果没选中,则选中
      arr[i].checked = true;
    }
  }
}
</script>
</head>

<body>
<form name="form1">
<fieldset>
  <legend>选择你感兴趣的类别</legend>
  <input type="checkbox" name="hobby" value="音乐" />音乐
  <input type="checkbox" name="hobby" value="看书" />看书
  <input type="checkbox" name="hobby" value="体育" />体育
  <input type="checkbox" name="hobby" value="足球" />足球
  <input type="checkbox" name="hobby" value="电脑" />电脑<br />
  <input type="checkbox" name="hobby" value="小说" />小说
  <input type="checkbox" name="hobby" value="文学" />文学
  <input type="checkbox" name="hobby" value="动漫" />动漫
  <input type="checkbox" name="hobby" value="经济" />经济
  <input type="checkbox" name="hobby" value="电影" />电影<br />
  <input type="checkbox" name="hobby" value="美术" />美术
  <input type="checkbox" name="hobby" value="管理" />管理
  <input type="checkbox" name="hobby" value="历史" />历史
  <input type="checkbox" name="hobby" value="旅游" />旅游
  <input type="checkbox" name="hobby" value="戏剧" />戏剧
</fieldset>
  <input type="checkbox" onclick="select_all(this)" value="全选" />全选
  <input type="checkbox" onclick="select_no_all()" value="反选" />反选
</form>

</body>
</html>

I hope this article will be helpful to everyone learning JavaScript programming.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn