Question

I'm trying to build a form that has a radio buttons with two values in the top 1 and 2. If the radio button with the value of 1 is checked, I want one input box with the id = facebook to hide. On load, there's no radio button checked. This is my code:

$("input[name='accountType']").change(function(){

    var radio;
    radio = $("input[name='accountType']").val();

    if(radio === '1'){
        ("#facebook").hide();
    }

});

This is my HTML

<input type="text" name="facebook" id="facebook" value="" class="form-control">


<input type="radio" name="accountType" id="accountType-1" value="1" class="icheck" >
<input type="radio" name="accountType" id="accountType-2" value="2" class="icheck" >

I'm sure its obvious but I'm just starting to work with jQuery and I've tried different answers here but they don't work.

What am I doing wrong?

Was it helpful?

Solution

It's more simple:

$('input[name=accountType]').change(function(){
  $('#facebook').toggle(this.value !== '1');
});

Demo. First, change event is fired on the radio button that's checked, so there's no need to look for it with the full selector again - this would refer to the corresponding element, and this.value will give you its value.

Second, there's a convenient .toggle jQuery method that can be used to show or hide the element depending on some condition (show if it's truthy, hide if falsy). In this case, you need to hide the element if this.value is equal to '1', that's why I reverse the check (with !==).

As a sidenote, I've removed the quotation marks around 'accountType' - these are not required if attribute value (in attribute selector) is a valid JS identifier.

OTHER TIPS

This is what I would do

$('input[name=accountType]').change(function(){
if($('#accountType-1').is(':checked')) { $('#facebook').css('display', "none"); }

 });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top