Jquery: Select Radio

Hi there,

I’m trying to make a form element only appear if a radio button has been selected.

I have two buttons (yes and no).

If Yes is selected I’d like a text input field to appear.

I have the following:

		<script>
		
		            $('input:radio[name:scheme]').click(function() {
						if($("#radio-yes").is('checked')) {
							$('#provider').show();
            }
			else {$("#provider").hide();
};		
					})
		</script>

my group of radio buttons are named “scheme”. I have tried this from a few angles but can’t crack it. Ideally I’d like to use input:radio[value:yes]. It’s already a required value due to the JQuery validation plugin, and I simply need it to make the other field visible when yes is clicked on.

Any help would be greatfully received. My apologies for the simplicity of what I’m trying to achieve!

Try this


// Hide the provider 
$("#provider").hide();

// On change...
$('input:radio[name:scheme]').on(
	'change', 
	function() {
		if(this.value === 'Yes') {
			$('#provider').show();
		} else {
			$("#provider").hide();
		}		
	}
);	

Here is a fiddle to test: http://jsfiddle.net/Wg7ws/

It’s ok I managed to sort it. Excellent, I am now happy. However, I am now trying to use the JQuery validation plugin… on a multi page form… ARRRGGHHH. Any ideas how to make it validate before undertaking the button action? It validates in real time of course, but it still allows you to go to page 2 even if you’ve not filled it out. The only solution I can think of is to make 2 different forms, risking half data collection.

You can have just the rules for page 1, and use the page 2 button to add rules that are required for the second page.
Also, you can use the submitHandler event of the validator so that you can ensure that certain things have taken place before you allow it to be submitted.

Hold on a minute.

I can sort of understand what you’re saying…

  1. If you click the “Continue to Page 2” button (albeit with higher converting text)
  2. It adds the class “validate” or “required” or whatever, to the fields on page 2.

Fine.

However, it would still move to page two without validating page 1. Am I wrong here?

P.s. that fiddle business is really cool!

That button can trigger the validation routine for page 1, and restrict access to page 2 until after page 1 validates without any trouble.

Hmm… ok I’m not sure how to do this, methinks more reasearch. The problem is it’s not on two actual pages currently. JQuery simply hides one part of the form and magically appears it and disappears the other part one the button click (good old fashioned magic, you can’t beat it).

So I am currently putting

$(“#button”).click().validate(), but it doesn’t work. It still allows the next part of the page to show… hmmmm