Ajax validation problems

I’ve got a form that is submitted using ajax. The problem is that although I’ve got it to check if everything else if filled out or not I can’t get it to check if the confirm button is checked or not. This is what I’ve got but it’s just not adding ‘error’ to the confirm-box div :frowning:

Form code:

<div id="confirm-box" class="input_input" style="padding: 5px;">
Yes: <input id="confirm" type="radio" name="confirm" value="1"> No: <input id="confirm" type="radio" name="confirm" value="2">
</div>

Validation code:

$("#submit").on("click", function(){
var confirm    = $("#confirm").val();
var confirm length    = confirm;
    			
if(confirm.checked == false) {
$("#confirm-box").addClass("error");
}
else if(confirm.checked == true){
$("#confirm-box").removeClass("error");
}

I could be wrong, but I believe that “confirm” is a reserved word in JavaScript due to “confirm()”. Give it a different ID and name and see if that fixes it.

HTH,

:slight_smile:

UPDATE: Also, you are setting a variable called “confirm” to the value of the radio. If the radio isn’t checked, it doesn’t exist. Also, if there are two radio inputs named the same, you check which one is checked by comparing “radioName[0]” and “radioName[1]” checked status.

I tried changing the name to terms_agree but that didn’t work.

I understand what you’re saying about it not existing if it’s not checked but how would I write that? Is this right:

if(terms_agree.radioName[0] == false || terms_agree.radioName[1] 
 == false) {
$("#terms-box").addClass("error");
}
else if(terms_agree.radioName[0] == true || terms_agree.radioName[1]  == true){
$("#terms-box").removeClass("error");
}

Also is the ‘radioName’ number (the [0] and [1]) assigned automatically?

“radioName” is my pseudo-code, not an actual JS convention. If you give a variable name “terms_agree” the object (radio input) that is named “terms_agree”…

var terms_agree = document.formName.terms_agree; // or in jQuery, var terms_agree = $('#terms_agree');

// Again, “formName” is pseudo-code - use the actual form name in its place.

if(!terms_agree[0].checked && !terms_agree[1].checked){ // Exclamation point means "not"
     .... error code.. 
}

HTH,

:slight_smile:

Thank you, sorry for my dumbness at not realising radioName was pseudo-code, I should have spotted the obvious D’oh

I’m guessing if I want to check if only one of them is checked then I use || instead of &&

Thanks again though

If you only want to check for one of them, then you won’t need && or ||; just check for the one. The other won’t be needed.

And, there was no ‘dumbness’ involved, seriously. Everybody gotta start SOMEwhere. Right? :smile:

HTH,

:slight_smile:

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.