So I have this form, sent via jQuery ajax, but I’d like to validate the fields. I know how to validate the normal input fields, but the radio buttons and checkboxes are causing trouble. Here’s my code that validates the form and sends it, and displays the result.
$(function() {
$("#submit").click(function() {
var kysymys1 = $.trim($("input.kysymys1").val());
if (kysymys1 == "") {
alert('Täytä kaikki kentät.');
return false;
}
var kysymys2 = $.trim($("input.kysymys2").val());
if (kysymys2 == "") {
alert('Täytä kaikki kentät.');
return false;
}
var kysymys3 = $.trim($("input.kysymys3").val());
if (kysymys3 == "") {
alert('Täytä kaikki kentät.');
return false;
}
var dataString = $('#service-test').serialize();
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "../quiz.php",
data: dataString,
dataType: "text",
error: function(){ alert ('Nyt jotakin meni kyllä pahemman kerran pieleen. Yritä uudelleen?');
},
success: function(data) {
$("#result").html(data);
$('#service-test').fadeOut('slow');
}
});
return false;
});
});
And the form itself:
<div style="border:1px solid grey;">
<div id="result" style="padding:2%;"></div>
<form id="service-test" action="#" method="../quiz.php" style="padding:2%;">
Muuttuuko sivujen sisältö usein?
<input type="radio" name="muuttuminen" value="Kylla" class="kysymys1" /> Kyllä
<input type="radio" name="muuttuminen" value="Ei" class="kysymys1" />Ei
Mitä näistä voisit haluta sivuillesi?
<input type="checkbox" name="possiblecontent" value="Kuvagallerian" class="kysymys2" />Kuvagallerian
<input type="checkbox" name="possiblecontent" value="Pieni verkkokauppa" class="kysymys2" />Pieni verkkokauppa
<input type="checkbox" name="possiblecontent" value="Isompi verkkokauppa" class="kysymys2" />Isompi verkkokauppa
<input type="checkbox" name="possiblecontent" value="Jotain muuta" class="kysymys2" />Jotain muuta
Millaisen ulkoasun haluaisit?
<input type="radio" name="ulkoasu" value="Massasta erottuvan, uniikin ulkoasun" class="kysymys4" /> Massasta erottuvan, uniikin ulkoasun
<input type="radio" name="ulkoasu" value="Jotain muuta" class="kysymys3" /> Jotain muuta
<input id="submit" type="submit" /></form>
</div>
However, the validation part doesn’t do anything if user wont choose.
Here’s a jsfidde too:
http://jsfiddle.net/ducVP/4/
In stead of checking the value, you want to check if the checkbox/radio button has been selected..
So try this
This checks if the checkbox is checked, and if it isn’t then it does the alert.
Edit
Why not just have one of the radio buttons checked as default?