开发者

checkbox list -javascript

In my aspx page i am having a checkbox list ..It has binded values from a table.. I need to validate the checkbox list ..I tried the following script

 var checkBoxCount = 0;     

        var elements = document.getElementById('<%=ChkBoxList.ClientID%>');

        for(i=0; i<elements.length;i++)

        {

        if(elements[i].checked) 

        checkBoxCount++;

        }  

        if (checkBoxCount == 0)
               {
                alert("Please choose atleast one");
              return false;
              }

But I can't get the required output, it requires to select all the values in the checkbox list ..My need is atleast only one item must be selected fro开发者_如何转开发m the checkbox list.. Using javascript

Thanks in advance...


function readListControl()
{
 var tableBody = document.getElementById('CheckBoxList1').childNodes[0];

 for (var i=0;i<tableBody.childNodes.length; i++)
 {
  var currentTd = tableBody.childNodes[i].childNodes[0];
  var listControl = currentTd.childNodes[0];

  if ( listControl.checked == true )
   alert('#' + i + ': is checked');
 }
}


document.getElementById returns an element, not an array.

One way to do this would be to get the container and iterate through the inputs, like so:

var container = document.getElementById('<%=ChkBoxList.ClientID%>').parentNode;
var inputs = container.getElementsByTagName('input');

for (var i=0; i<inputs.length; i++) {
  if (typeof inputs[i] = "checkbox") {
    // statements
  }
}

You may also want to qualify the inputs with more conditional statements. This just gives you the broad brush strokes.


You will have to show us your generated html.

However, here is a working example:

<html>
<body><form name="myform" method="POST" action="" onsubmit="return validate();">
<input type="checkbox" name="mybox" value="1" /> 1 
<input type="checkbox" name="mybox" value="2" /> 2 
<input type="checkbox" name="mybox" value="3" /> 3 
<input type="checkbox" name="mybox" value="4" /> 4 
<input type="checkbox" name="mybox" value="5" /> 5 
<input type="submit" value="Submit Form" />
</form>

<script type = "text/javascript">
function validate() {
    var checkBoxCount = 0;
    for (var i = 0; i< 5; i++) {
        if(document.myform["mybox"][i].checked){
            checkBoxCount ++;
        }
    }
    if (checkBoxCount == 0) {
        alert ("Tick a box!");
        return false;
    }
    return true;
}
</script>
</body>
</html>


var k=0; var ControlRef = document.getElementById('ChkBoxList'); var CheckBoxListArray = ControlRef.getElementsByTagName('input'); for (var i=0; i

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜