David
David

Reputation: 139

Validating radiobuttons in jquery

I'm using the following to make sure fields aren't empty before they get posted in jquery:

if(this.field.value == "") {
  jQuery( ".page-error-message" ).remove();
  jQuery(".top").append(jQuery("field required"));
  jQuery('html, body').animate({ scrollTop: 0 }, 'slow');
   return;
}

I have some radio buttons that need yes selected, however it doesn't seem to work if I do say:

if(this.radiobutton.value == "no") {
  jQuery( ".page-error-message" ).remove();
  jQuery(".top").append(jQuery("field must be yes"));
  jQuery('html, body').animate({ scrollTop: 0 }, 'slow');
   return;
}

What am I doing wrong?

Upvotes: 3

Views: 82

Answers (3)

napster3world
napster3world

Reputation: 366

Try this. Assign at your radio buttons an id example "radio_button" and use this for all.

if($('#radio_button').is(':not(:checked)'))  {
  jQuery( ".page-error-message" ).remove();
  jQuery(".top").append(jQuery("field must be yes"));
  jQuery('html, body').animate({ scrollTop: 0 }, 'slow');
   return;
}

if you have any other fields you can choose to use selectors like this

if($('#radio_button [name="example"]').is(':not(:checked)'))  {
  jQuery( ".page-error-message" ).remove();
  jQuery(".top").append(jQuery("field must be yes"));
  jQuery('html, body').animate({ scrollTop: 0 }, 'slow');
   return;
}

Upvotes: 0

Jai
Jai

Reputation: 74738

I think you should try to check if any radio is chekced or not if checked then what value does it have if no then validate it, Try with this :

if($(':radio', this).prop(':checked') || $(':radio:checked', this).val() == "no") {
  jQuery( ".page-error-message" ).remove();
  //jQuery(".top").append(jQuery("field must be yes"));
  jQuery(".top").append("field must be yes");
  jQuery('html, body').animate({ scrollTop: 0 }, 'slow');
  return;
}

jQuery(".top").append(jQuery("field must be yes")); this seems a little bit confusing to me, i think this should be something like:

jQuery(".top").append("field must be yes");

Upvotes: 0

Kevin Choppin
Kevin Choppin

Reputation: 394

Radio buttons have multiple fields. You're better checking that the no button is checked.

eg;

if(this.radiobutton.checked) {
  jQuery( ".page-error-message" ).remove();
  jQuery(".top").append(jQuery("field must be yes"));
  jQuery('html, body').animate({ scrollTop: 0 }, 'slow');
  return;
}

Where radiobutton is the radio button with a value of no.

Upvotes: 1

Related Questions