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 & any of dogs -> play music
- Dog & dog -> play music
- Nothing -> form action
HTML:
<section class="pets">
<form action="sample_action" method="get">
<input type="hidden" name="sample_name" value="sample_value">
<ul>
<li><input id="checkbox1" type="checkbox" name="pet" value="cat"><label for="checkbox1">Cat</label></li>
<li><input id="checkbox2" type="checkbox" name="pet" value="dog"><label for="checkbox2">Dog 1</label></li>
<li><input id="checkbox3" type="checkbox" name="pet" value="dog"><label for="checkbox3">Dog 2</label></li>
</ul>
<button type="submit">Check my pets</button>
</form>
</section>
Solution:
function checkPets () {
var cat = $('#checkbox1').is(":checked");
var dog1 = $('#checkbox2').is(":checked");
var dog2 = $('#checkbox3').is(":checked");
return !cat &&(dog1 || dog2);
}
$(window).load(function(){
$('.pets form').submit( function(e){
if(checkPets()) {
e.preventDefault();
$('body').append('<audio></audio>');
$('audio').attr({'src': 'audio.mp3', 'autoplay': 'autoplay'});
}
});