Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using jQuery, hide a textbox if a radio button is selected

I have 2 radio buttons, what I want is if a user selects the top radio button then hide a textbox.

Not sure how to bind an event to a radio button.

like image 919
Blankman Avatar asked Mar 28 '10 20:03

Blankman


People also ask

How do you show and hide input fields based on radio button selection in jQuery?

To show or hide an element when a radio button is selected: Add a click event handler to all input elements of type radio . Each time a radio button is selected, check if it is the button that should show the element. If it is, set the display property of the hidden element to block .

How do you show and hide div elements based on the selection of radio buttons in jQuery?

Answer: Use the jQuery show() and hide() methods You can simply use the jQuery show() and hide() methods to show and hide the div elements based on the selection of radio buttons. The div boxes in the following example are hidden by default using the CSS display property which value is set to none .

How do you display a TextBox when a radio button is selected?

When the RadioButton is clicked, the ShowHideDiv JavaScript function is executed. Inside this function, based on whether Yes RadioButton is checked (selected) or unchecked (unselected), the HTML DIV with TextBox is shown or hidden.


2 Answers

Something like this:

<input type="radio" name="foo" value="top" />
<input type="radio" name="foo" value="bottom" />

And in jQuery:

$('input[name=foo]').click(function() {
    if($(this).val() == "top") {
        $('#textbox').hide();
    } else {
        $('#textbox').show();
    }
});

click because change doesn't seem to work correctly on IE.

like image 69
Tatu Ulmanen Avatar answered Oct 01 '22 21:10

Tatu Ulmanen


This will allow you to add the event to a selected radio, in case your radio's do not have the same name.

$('checkbox-selector').click(function() {
    if ($(this).is(':checked')) {
      $('textbox-selector').hide();
    }
    else {
      $('textbox-selector').show();
    }
});
like image 21
Dustin Laine Avatar answered Oct 01 '22 20:10

Dustin Laine