I’m working with a CMS where it’s not possible to add an ID to the label. JQuery is available, but I’d like to learn how to do it both JQuery and JavaScript if possible.
And I need to add the class ‘res-required’ to the label when the form is submitted but no data given for the fields I’m checking against. I’m running the function checkform() on submit to currently check the name and email inputs and can get the class to appear on the input, but don’t know how to select the label if it doesn’t have an ID:
<script type="text/javascript">
function checkform(form) {
if (form.res_name.value == "") {
alert( "Please enter your name." );
if(document.getElementById && document.createTextNode) {
var n = document.getElementById('res_name');
if(n) {
// Check if class exists and do not overwrite if so (add with a preceding space)
n.className+=n.className?' res-required':'res-required';
}
}
form.res_name.focus();
return false;
}
if (form.res_email.value == "") {
alert( "Please enter an email address." );
form.res_email.focus();
return false;
}
return true ;
}
</script>
Great, that worked a treat, thanks - do you know how I’d mark all the labels for required inputs in one go? The approach I’m using marks one at a time:
<script type="text/javascript">
//<![CDATA[
function checkform(form) {
if (form.res_name.value == "") {
alert( "Please enter your name." );
document.getElementById('res_name').parentNode.firstChild.className = 'res-required';
form.res_name.focus();
return false;
}
if (form.res_email.value == "") {
alert( "Please enter an email address." );
document.getElementById('res_email').parentNode.firstChild.className = 'res-required';
form.res_email.focus();
return false;
}
return true ;
}
//]]>
</script>
Don’t quite follow you. You first have to check validity before changing the class. Why all in one go?
Note, if a field is valid, then remove the class ‘res-required’
On sites I’ve seen, all required fields are highlighted if you fail to fill in just one of them and submit the form. I was thinking it would be neater to have all the required fields highlighted at once instead of highlighting them one-by-one.
Re: your note, is there an easy way to remove the class? I was looking for a solution online, but it seems they all require making lengthy functions (is this why people use JQuery more these days as well - to cut down on code?).
I’m kind of coming at this the wrong way round, trying to learn JavaScript after learning some JQuery…