当前位置:编程学习 > JS >>

js 根据内容设置checkbox为选中状态

js 根据内容设置checkbox为选中状态
这是根据自己的需要写的一款,根据用户填写的内容,再自动判断checkbox值有存在用户输入的内容中不,如果存在就把当前checkbox状态设置为checked就ko了。


<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>

<body>
<form id="form1" name="form1" method="post" action="">
  <p>
    <label for="textfield"></label>
    <label for="textarea"></label>
    <textarea name="textarea" id="textarea" cols="45" rows="5" >a6,a1,你好,a2, a3, a4, a5 </textarea>
  </p>
  <table width="200">
    <tr>
      <td><label>
        <input type="checkbox" name="box[]" value="a1" id="a1" />
        a</label></td>
    </tr>
    <tr>
      <td><label>
        <input type="checkbox" name="box[]" value="a2" id="a2" />
        b</label></td>
    </tr>
    <tr>
      <td><label>
        <input type="checkbox" name="box[]" value="a3" id="你好" />
        c</label></td>
    </tr>
    <tr>
      <td><label>
        <input type="checkbox" name="box[]" value="a4" id="a4" />
        d</label></td>
    </tr>
    <tr>
      <td><label>
        <input type="checkbox" name="box[]" value="a5" id="666" />
        e</label></td>
    </tr>
  </table>
  <p>
    <input type="button" name="button" id="button" value="测试" onclick="setcheck();" />
    <input type="button" name="button2" id="button2" value="反向测试" onclick="setcheck1();" />
  </p>
</form>

<script language="网页特效">
 
 $=function(id)
 {
  return document.getelementbyid(id);
 }
 
 function setcheck1()
    {
        var m = document.getelementsbyname('box[]');
        var l = m.length;  
  var tvalue = $('textarea').value;
        for ( var i=0; i< l; i++)
        {        
     if(tvalue.indexof(m[i].value) != -1 )
     {
      m[i].checked = true;     
     }   
        }
  
    }
 
 function setcheck()
 {
  var tvalue = $('textarea').value;
  var tmp = tvalue.split(',');
  var array = new array();
  
  if( tmp.length > 0 )
  {
   for(var i=0;i<tmp.length;i++ )
   {
    var c = tmp[i].replace(" ", ""); 
    if( $(c) )
    {
     $(c).checked = true; 
    }
    else
    {
     array = c;
    }
    
   }
  }
  else
  {
   alert('没匹配到相关数据,请手动选择');
  }
  alert(array);
 }
 
 
</script>
</body>
</html>

补充:网页制作,js教程 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,