开发者

Dynmaic checkboxs validation

开发者 https://www.devze.com 2023-02-10 20:21 出处:网络
I want to validate Checkbox in javascript, checkboxes is开发者_如何学Python generating dynamically by PHP and name of checkboxes arelike \"checkbox1\" , \"checkbox2\" ,\"checkbox3\" i.e. incrementing

I want to validate Checkbox in javascript, checkboxes is开发者_如何学Python generating dynamically by PHP and name of checkboxes are like "checkbox1" , "checkbox2" ,"checkbox3" i.e. incrementing i++ and these numbers are coming from database, it might be first time only 2 rows fetched and next time 112 rows.

How i can make sure in javascript that atleast one checkbox must be selected.


// When you use jQuery... somehow like this
$('form').submit(function() {
    if ($("input:checked").length == 0) {
        alert('Please check at least one checkbox!');
        return false;
    }
});


If you do not want to use any js framework, then just give the same name attribute to the checkboxes

Assuming your checkboxes are named test

var chkBoxes = document.getElementsByName("test");
  var chked=0;
  for(var i=0;i<chkBoxes.length;i++)
  {
    if(chkBoxes[i].checked)
        chked++;
  }
  if(chked===0)
     alert("Please select a value");

Added as per the sample code specified in the comment

function isChecked()
{
  var i=1; 
  var chkd=0;
  var elem = "";
  var chkForMoreChkBoxes=true;
  do{
        elem=document.getElementById("check_"+i);
        try{
            if(elem.checked)
            {
                chkd++;
            }
            i++;
        }
        catch(err)
        {
            chkForMoreChkBoxes=false;
        }
  }while(chkForMoreChkBoxes)
  if(chkd===0)
  {
    alert("Please select a value");
    return false;
  }

}
0

精彩评论

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