0

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?

1
  • 2
    can you share the html of checkboxes Commented May 14, 2013 at 4:44

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Arun for this simple and logical answer. Your solution works fine. But populating the array troubles me. If we select sun, wed, thur, fri, sat(which is correct order) and if we use $.each it will return 1,4,5,6,7 instead of 4,5,6,7,1. Then this solution will not work. Is there a way to populate the array as we need using $.each?
0
 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.