188

I have these 2 radio buttons at the moment so that the user can decide whether they need postage included in the price or not:

<input type="radio" id="postageyes" name="postage" value="Yes" /> Yes <input type="radio" id="postageno" name="postage" value="No" /> No 

I need to use Jquery to check if the 'yes' radio button is checked, and if it is, do an append function. Could someone tell me how I'd do this please?

Thanks for any help

edit:

I've updated my code to this, but it's not working. Am I doing something wrong?

<script type='text/javascript'> // <![CDATA[ jQuery(document).ready(function(){ $('input:radio[name="postage"]').change(function(){ if($(this).val() == 'Yes'){ alert("test"); } }); }); // ]]> </script> 
0

10 Answers 10

336
$('input:radio[name="postage"]').change( function(){ if ($(this).is(':checked') && $(this).val() == 'Yes') { // append goes here } }); 

Or, the above - again - using a little less superfluous jQuery:

$('input:radio[name="postage"]').change( function(){ if (this.checked && this.value == 'Yes') { // note that, as per comments, the 'changed' // <input> will *always* be checked, as the change // event only fires on checking an <input>, not // on un-checking it. // append goes here } }); 

Revised (improved-some) jQuery:

// defines a div element with the text "You're appendin'!" // assigns that div to the variable 'appended' var appended = $('<div />').text("You're appendin'!"); // assigns the 'id' of "appended" to the 'appended' element appended.id = 'appended'; // 1. selects '<input type="radio" />' elements with the 'name' attribute of 'postage' // 2. assigns the onChange/onchange event handler $('input:radio[name="postage"]').change( function(){ // checks that the clicked radio button is the one of value 'Yes' // the value of the element is the one that's checked (as noted by @shef in comments) if ($(this).val() == 'Yes') { // appends the 'appended' element to the 'body' tag $(appended).appendTo('body'); } else { // if it's the 'No' button removes the 'appended' element. $(appended).remove(); } }); 

var appended = $('<div />').text("You're appendin'!"); appended.id = 'appended'; $('input:radio[name="postage"]').change(function() { if ($(this).val() == 'Yes') { $(appended).appendTo('body'); } else { $(appended).remove(); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script> <input type="radio" id="postageyes" name="postage" value="Yes" />Yes <input type="radio" id="postageno" name="postage" value="No" />No

JS Fiddle demo.

And, further, a mild update (since I was editing to include Snippets as well as the JS Fiddle links), in order to wrap the <input /> elements with <label>s - allow for clicking the text to update the relevant <input /> - and changing the means of creating the content to append:

var appended = $('<div />', { 'id': 'appended', 'text': 'Appended content' }); $('input:radio[name="postage"]').change(function() { if ($(this).val() == 'Yes') { $(appended).appendTo('body'); } else { $(appended).remove(); } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label> <input type="radio" id="postageyes" name="postage" value="Yes" />Yes</label> <label> <input type="radio" id="postageno" name="postage" value="No" />No</label>

JS Fiddle demo.

Also, if you only need to show content depending on which element is checked by the user, a slight update that will toggle visibility using an explicit show/hide:

// caching a reference to the dependant/conditional content: var conditionalContent = $('#conditional'), // caching a reference to the group of inputs, since we're using that // same group twice: group = $('input[type=radio][name=postage]'); // binding the change event-handler: group.change(function() { // toggling the visibility of the conditionalContent, which will // be shown if the assessment returns true and hidden otherwise: conditionalContent.toggle(group.filter(':checked').val() === 'Yes'); // triggering the change event on the group, to appropriately show/hide // the conditionalContent on page-load/DOM-ready: }).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label> <input type="radio" id="postageyes" name="postage" value="Yes" />Yes</label> <label> <input type="radio" id="postageno" name="postage" value="No" />No</label> <div id="conditional"> <p>This should only show when the 'Yes' radio &lt;input&gt; element is checked.</p> </div>

And, finally, using just CSS:

/* setting the default of the conditionally-displayed content to hidden: */ #conditional { display: none; } /* if the #postageyes element is checked then the general sibling of that element, with the id of 'conditional', will be shown: */ #postageyes:checked ~ #conditional { display: block; }
<!-- note that the <input> elements are now not wrapped in the <label> elements, in order that the #conditional element is a (subsequent) sibling of the radio <input> elements: --> <input type="radio" id="postageyes" name="postage" value="Yes" /> <label for="postageyes">Yes</label> <input type="radio" id="postageno" name="postage" value="No" /> <label for="postageno">No</label> <div id="conditional"> <p>This should only show when the 'Yes' radio &lt;input&gt; element is checked.</p> </div>

JS Fiddle demo.

References:

Sign up to request clarification or add additional context in comments.

2 Comments

No need to see if it is checked or not. It will never have the value otherwise. Waste of resources!
if ($(this).is(':checked') && $(this).val() == 'Yes') >>>>>> if ($(this).is(':checked'))
28

Try this

if($("input:radio[name=postage]").is(":checked")){ //Code to append goes here } 

Comments

18

Something like this:

if($('#postageyes').is(':checked')) { // do stuff } 

3 Comments

The jQuery object is always truthy. You might want to use $(...).length instead.
You mean #postageyes:checked or $('#postageyes').is(':checked')?
@pimvdb According the jQuery docs, is() returns a boolean. So calling .length() is broken. From the docs: "Unlike other filtering methods, .is() does not create a new jQuery object. Instead, it allows you to test the contents of a jQuery object without modification." -- api.jquery.com/is
7
if($('#test2').is(':checked')) { $(this).append('stuff'); } 

Comments

7
$('input:radio[name="postage"]').change(function(){ if($(this).val() === 'Yes'){ // append stuff } }); 

This will listen for a change event on the radio buttons. At the time the user clicks Yes, the event will fire and you will be able to append anything you like to the DOM.

Comments

4
$("input").bind('click', function(e){ if ($(this).val() == 'Yes') { $("body").append('whatever'); } }); 

2 Comments

Not too sure about this but, won't $("#postageyes:checked" always return true? Wouldn't you have to use the .length for it to work?
removed "or" and everything after that
3

Try this:

if ( jQuery('#postageyes').is(':checked') ){ ... } 

Comments

1

This will listen to the changed event. I have tried the answers from others but those did not work for me and finally, this one worked.

$('input:radio[name="postage"]').change(function(){ if($(this).is(":checked")){ alert("lksdahflk"); } }); 

Comments

1

Another implementation could be this one:

HTML

<h1>Display Radio Buttons</h1> <form action="/action_page.php"> <p>Please select your favorite Web language:</p> <!-- 1 --> <input type="radio" id="html" name="fav_language" value="HTML" checked> <label for="html">HTML</label><br> <!-- 2 --> <input type="radio" id="css" name="fav_language" value="CSS"> <label for="css">CSS</label><br> <!-- 3 --> <input type="radio" id="javascript" name="fav_language" value="JavaScript"> <label for="javascript">JavaScript</label> <br> <input type="submit" value="Submit"> </form> 

Remember:

  • name: groups the radio buttons.
  • id: tells what's the state of every radio button.
  • value: It's what you'll post on submit.
  • for: Allows you to associate the given label to the id named input field.
  • Submit button: Will POST the selected radio button value to the web server (back-end).

jQuery

Remember this is code front-end.

Here you'll select all buttons by type, and do whatever you want with your selection. In this case, we'll be using the value part of the HTML element:

$("[type='radio']").on('change', function (e) { var selectedValue = $(this).val(); console.log(selectedValue); // So you can see it in the console. if (selectedValue == 'HTML') { // Do something. } else { // Or do something else. // Example: // someOtherSelectedElement.prop("disabled", false); } }); 

Add as many if statements as you may need to you radio buttons.

Keep in mind that thanks to the use of value field you can set up as many options as you want.

Result

enter image description here

Live code

References

Comments

0
jQuery('input[name="inputName"]:checked').val() 

2 Comments

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
Got it. Next answer will have one.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.