user579984
user579984

Reputation: 160

jquery show and hide div issue

I have created an editable form that allows users to edit their profile information. This form can be saved and revisted so I need to be able to save the updates as the user goes along. This is working ok.

The form is very long so in some sections I have fields that show / hide using jquery depending on the yes or no selections for a previous input. This also works except that if a radio input is selected and saved whe the form is revisted the jquery has hidden the details field again.

So what I need is some help amending the following jquery code so that if neither radio button is seleced the details div is hidden but if the Yes option is selected and saved it will automatically open when the form is revisted! Thanks

$("#diet-details").hide();
$("input[name=diet]").click(function() {
    if ( $("#diet1").attr('checked'))
        $("#diet-details").hide();

    if ( $("#diet2").attr('checked'))
        $("#diet-details").show();
});      

Upvotes: 0

Views: 83

Answers (3)

cacoroto
cacoroto

Reputation: 279

A way to do that would be:

(function(){
    var $d1 = $("#diet1"),
        $d2 = $("#diet2"),
        $details = $("#diet-details");

    !$d2.prop('checked') && $details.hide();

    $("input[name=diet]").click(function() {
        $d1.prop('checked') && $details.hide();
        $d2.prop('checked') && $details.show();
    });
})();  

Upvotes: 0

Mark Schultheiss
Mark Schultheiss

Reputation: 34227

another way to set initial state:

function checkem() {
  if ($("#diet1").prop('checked')) $("#diet-details").hide();
  if ($("#diet2").prop('checked')) $("#diet-details").show();
}
$("input[name=diet]").click(function () {
  checkem();
});
checkem(); //sets initial state based one current

test fiddle:http://jsfiddle.net/YqUhZ/

IF you want it to show if NEITHER is checked then:

function checkem() {
  if ($("input[name=diet]:checked").length) {
    $("#diet-details").hide();
  } else {
    $("#diet-details").show();
  }
}
$("input[name=diet]").change(function () {
  checkem();
});
checkem(); //sets initial state based one current

Upvotes: 0

Bassam Mehanni
Bassam Mehanni

Reputation: 14944

You can pass the show/hide condition to the toggle function, and instead of always hiding the diet-details div in the beginning, check if diet1 option is checked and show it (or hide it) based on that,

$(function() {
  $('#diet-details').toggle($("#diet1").is(':checked'));

  $("input[name=diet]").click(function() {
    $('#diet-details').toggle($("#diet1").is(':checked'));
  }); 
});

Upvotes: 1

Related Questions