JS form verification I have three checboxes in my form. I have to check which one is checked and start the action. What do you think? Is this the easiest way of doing it?


Checkbox 1 = cat
Checkbox 2 = dog
Checkbox 3 = dog
Only cat ->           form action
Cat &amp; any of dogs ->  play music
Dog &amp; dog ->          play music
Nothing ->            form action


HTML:

&lt;section class="pets"&gt;
    &lt;form action="sample_action" method="get"&gt;
            &lt;input type="hidden" name="sample_name" value="sample_value"&gt;
          &lt;ul&gt;
            &lt;li&gt;&lt;input id="checkbox1" type="checkbox" name="pet" value="cat"&gt;&lt;label for="checkbox1"&gt;Cat&lt;/label&gt;&lt;/li&gt;
            &lt;li&gt;&lt;input id="checkbox2" type="checkbox" name="pet" value="dog"&gt;&lt;label for="checkbox2"&gt;Dog 1&lt;/label&gt;&lt;/li&gt;
            &lt;li&gt;&lt;input id="checkbox3" type="checkbox" name="pet" value="dog"&gt;&lt;label for="checkbox3"&gt;Dog 2&lt;/label&gt;&lt;/li&gt;
          &lt;/ul&gt;
          &lt;button type="submit"&gt;Check my pets&lt;/button&gt;
   &lt;/form&gt;
&lt;/section&gt;


Solution:

function checkPets () {
  var cat = $('#checkbox1').is(":checked");
  var dog1 = $('#checkbox2').is(":checked");
  var dog2 = $('#checkbox3').is(":checked");
  return !cat &amp;&amp;(dog1 || dog2);
}

$(window).load(function(){
$('.pets form').submit( function(e){
    if(checkPets()) {
        e.preventDefault();
        $('body').append('&lt;audio&gt;&lt;/audio&gt;');
        $('audio').attr({'src': 'audio.mp3', 'autoplay': 'autoplay'});
    }
});
Is this the easiest way of doing it?


In my view, yes: I don't see how to dramatically simplify your code.
It only can be (very) slightly reduced using return false; instead of e.preventDefault;.  

You also might use the more common $(document).ready() in place of $(window).load().
BTW it'd be more readable to rename your checkPets() function to something like mustPlayMusic(), which reflects that it returns a boolean.

So it results in:

$(document).ready(function(){
  $('.pets form').submit( function(e){
    if(mustPlayMusic()) {
      $('body').append('&lt;audio&gt;&lt;/audio&gt;');
      $('audio').attr({'src': 'audio.mp3', 'autoplay': 'autoplay'});
      return false;
    }
});


On the other hand, something puzzles me: the checkPets()||mustPlayMusic() function doesn't match the conditions you detailed above.  

It should be:

function checkPets () {
  var cat = $('#checkbox1').is(":checked");
  var dog1 = $('#checkbox2').is(":checked");
  var dog2 = $('#checkbox3').is(":checked");
  return (cat &amp;&amp; (dog1 || dog2)) || (dog1 &amp;&amp; dog2);
}