Search code examples
javascriptjquerycode-readability

JQuery: Alternative to each() for conditional check against selected checkbox values


1) Checkboxes has five values: GRA, RRA, FRA, MRA, CHDA

2) Checkbox class Name is oops. Common for all 5.

3) We shall throw an exception if FRA, MRA, CHDA value is not selected

4) Following is snippet i am using to achieve this:

var availability = false;

$(".oops:checked").each(function() {
    if($(this).val() === 'FRA' || $(this).val() === 'MRA' || $(this).val() === 'CHDA') {
        availability = true;
    }
});

if (!availability) {
    errors.push('There is no selected among FRA MRA CHRA');            
}

Do we have other better approach to handle this instead of using three or operators and check it in each() function?


Solution

  • You can create a array data structure for all the allowed values for the checkbox and check the selected values against them:

    var availability = false;
    var alloweValues = ['FRA', 'MRA', 'CHDA']; 
    $(".oops:checked").each(function() {
        if(alloweValues.includes($(this).val())) {
          availability = true;
        }
    });
    if (!availability) {
        errors.push('There is no selected among FRA MRA CHRA');            
    }
    

    You can further refactor your code to:

    var availability = false;
    var alloweValues = ['FRA', 'MRA', 'CHDA']; 
    $(".oops:checked").each(function() {
        availability = alloweValues.includes($(this).val());
    });
    if (!availability) {
        errors.push('There is no selected among FRA MRA CHRA');            
    }
    

    You can also replace includes() with indexOf() like

    alloweValues.indexOf($(this).val()) !== -1
    

    As, includes() do not work in IE browser.