0
votes

I have checkboxes like below which shows all the days of a week.

enter image description here

The value of checkboxes are 1, 2, 3, 4, 5, 6, 7 respectively.

I need to have a validation logic in javascript which validates whether the user clicks the checkboxes which are continuous days. The continuous days can start from any day. Like,

Wednesday, Thursday, Friday, Saturday, Sunday (4,5,6,7,1)

Monday, Tuesday, Wednesday, Thursday, Friday, Saturday(2,3,4,5,6,7)

Saturday, Sunday, Monday, Tuesday, Wednesday, Thursday(7,1,2,3,4,5)

Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday(3,4,5,6,7,1) etc.

Minimum of 5 days should be selected. The user should not be allowed to select like below examples:

Saturday, Sunday, Monday, Wednesday, Thursday(7,1,2,4,5)

Monday, Wednesday, Thursday, Friday, Saturday(2,4,5,6,7)

Tuesday, Thursday, Friday, Saturday, Sunday(3,5,6,7,1)

Is there any way to handle this validation in javascript/jquery?

2
can you share the html of checkboxesArun P Johny

2 Answers

1
votes

If you can get the selected values into an array then

function test(values){

    if(values.length !=5 ){
        return false;
    }

    var expected = values[0], valid = true;
    $.each(values, function(i, v){
        if( expected != v){
            valid = false;
            return false;
        }
        expected  = v == 7 ? 1 : v + 1;
    })

    if(!valid){
        return false;
    }

    return true;
}

Demo: Fiddle

0
votes
 function checkboxlimit(checkgroup, limit){
var checkgroup=checkgroup
var limit=limit
for (var i=0; i<checkgroup.length; i++){
    checkgroup[i].onclick=function(){
    var checkedcount=0
    for (var i=0; i<checkgroup.length; i++)
        checkedcount+=(checkgroup[i].checked)? 1 : 0
    if (checkedcount>limit){
        alert("You can only select a maximum of "+limit+" checkboxes")
        this.checked=false
        }
    }
}
 }

ADD THIS IN BODY SECTION

  checkboxlimit(document.forms.world.countries, 2) // here 2 states to select only two check box