Show/Hide Divs based on Radio Buttons with checked values coming from a database

I’ve got show/hide working great using Jquery depending on a radio value, but when the radio is checked automatically depending on a database value, not so much.

On my form

<input type="radio" name="bn" value="0" <?php if($tE['bn'] <1){echo 'checked="checked"';} ?> > No
<input type="radio" name="bn" value="1" <?php if($tE['bn']==1){echo 'checked="checked"';} ?> > Yes
<input type="radio" name="bn" value="2" <?php if($tE['bn']==2){echo 'checked="checked"';} ?> > Multiple

… and the associated script:

  $(document).ready(function(){
  $("input[name$='bn']").click(function(){
  var radio_value = $(this).val();
  if(radio_value=='0') {
    $("#onebn").hide("slow");
    $("#multibn").hide("slow");
  }
  else if(radio_value=='1') {
    $("#onebn").show("slow");
    $("#multibn").hide("slow");
  }
  else if(radio_value=='2') {
    $("#multibn").show("slow");
    $("#onebn").hide("slow");
   }
  });
});

What do I need to change to get the script to take the preselected (checked) value into consideratoin?

Are you wanting to trigger the selected radio button on page load? That should be as easy as adding the following just before the end of the document ready function:

$('[name="bn"]:checked').trigger('click');

You can see a quick example of this at http://jsfiddle.net/s0p2kp3m/

1 Like

Ahh - that did it, and I understand why too (which doesn’t always happen!!)
Thanks, Les

Just for fun but for modern browsers you could do this with css and no JS.

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<style>
#onebn,#multibn{opacity:0;transition:.5s ease;height:0;}
.bn1:checked ~ #onebn,
.bn1:checked ~ #multibn{opacity:0;height:0}
.bn2:checked ~ #multibn{opacity:0;height:0}
.bn2:checked ~ #onebn{opacity:1;height:auto;}
.bn3:checked ~ #onebn{opacity:0;height:0}
.bn3:checked ~ #multibn{opacity:1;height:auto;}
</style>
</head>

<body>
<input type="radio" class="bn1" name="bn" value="0" /> No
<input type="radio" class="bn2" name="bn" value="1" /> Yes
<input type="radio" class="bn3" name="bn" value="2" checked="checked" /> Multiple

<div id="onebn">One button</div>
<div id="multibn">Multiple buttons</div>
</body>
</html>

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.