0

When and only when a user selects 'once a day', i.e., value 2, I want a div class called #time-formgroup to be shown. Should the user click option 1 or 3 at anytime, for that div class to be hidden.

Currently, the div class is shown irrespective of what option they choose and stays shown!

HTML

<select id="Alert_Me" name="Alert_Me" class="form-control">
   <option value="1" selected="selected">Immediately</option>
   <option value="2">Once a day</option>
   <option value="3">Save</option>
</select>

jQuery

$("#Alert_Me").click(function(){      
  var frequency = $('input[name=Alert_Me]:checked').val();
  if(frequency = 2){
    $('#time-formgroup').removeClass('hidden');
  } else {
    $('#time-formgroup').addClass('hidden');
  }
});

Thank you in advanced.

  • use `==` and `2` might be a string. – Ben Felda Aug 19 '14 at 20:36
  • possible duplicate of [How to use jQuery to show/hide divs based on radio button selection?](http://stackoverflow.com/questions/2777139/how-to-use-jquery-to-show-hide-divs-based-on-radio-button-selection) – Brett Weber Aug 19 '14 at 20:36
  • @BenFelda .val() is always a string, but yeah, he's not comparing but assigning 2. Thus always showing. – Brunis Aug 19 '14 at 20:40

3 Answers3

1

This could be very easily done by one line of code. The toggle function can take a boolean parameter to determine if the element should be shown or hidden. Now we check if the value of the selected option equals 2 and make that the boolean parameter to determine if we should show or hide the time-formgroup div.

$("#Alert_Me").on("change", function () {
    $("#time-formgroup").toggle($(this).val() == 2);
});

FIDDLE

ZiNNED
  • 2,620
  • 20
  • 31
0

Heres a working example of what you want to achieve with jquery:

$(document).ready(function () {
    $('#domicilio').hide();
    $(".radio").change(function () { //use change event
        if (this.value == "domicilio") { //check value if it is domicilio
            $('#domicilio').stop(true,true).show(); //than show
        } else {
            $('#domicilio').stop(true,true).hide(); //else hide
        }
    });
});

Example: http://jsfiddle.net/btE53/3/

jagmitg
  • 4,236
  • 7
  • 25
  • 59
0

I made a couple changes. First, why not a simpler selector? I used ID instead of the name attribute. Then, I removed the :checked property. Doesn't seem necessary. Finally, I used the change event instead. Having the element disappear on click was a bit weird.

http://jsfiddle.net/isherwood/ejfqkssv/

$("#Alert_Me").change(function () {
    var frequency = $('#Alert_Me').val();

    if (frequency == 2) {
        $('#time-formgroup').removeClass('hidden');
    } else {
        $('#time-formgroup').addClass('hidden');
    }
});
isherwood
  • 58,414
  • 16
  • 114
  • 157