dac
dac

Reputation: 821

php/jQuery changing whether show/hide based on radio button setting from database

I'm still new at jQuery and struggling. Finally, I can get jQuery to toggle show/hide when the button is clicked. What I'm still struggling with now is how to get show/hide to match up with the state of the button on page load. The value is coming from the database using php. So I don't know what it will be. I'd really appreciate some help!

Basically, if the button with id of 'specify' is checked, the text in the div shows; if the 'open' button is checked, the text is hidden. I set up the css so the specify class for the div makes it hidden. Should I have done that?

Here is the code:

HTML

<input type="radio" name="volneed" id="open" class="required" value="open to all"
 <? if($thisvolneed=='open'){echo 'checked="checked"';} ?> />
<label for="open"> Open to all </label>

<input type="radio" name="volneed" id="specify"  class="required" value="specify"
<? if($thisvolneed=='specify'){echo 'checked="checked"';} ?> /> 
<label for="specify"> Specify types of volunteers needed </label>

<div class="specify"><p>Some info...</p></div>

CSS:

.specify{display:none;}

jQuery:

$(document).ready(function() {          
    $("#specify").change(function(evt) {
    evt.preventDefault();
    $(".specify").show();
    });

    $("#open").change(function(evt) {
    evt.preventDefault();
    $(".specify").hide();
    });
});

Upvotes: 0

Views: 1450

Answers (2)

KoolKabin
KoolKabin

Reputation: 17643

a small try:

<style>
.specify{display:none;}
</style>
<script src="jquery.min.js"></script>
<input type="radio" name="volneed" id="open" class="required myOption" value="open to all" checked="checked" />
<label for="open"> Open to all </label>

<input type="radio" name="volneed" id="specify"  class="required myOption" value="specify" /> 
<label for="specify"> Specify types of volunteers needed </label>

<div class="specify"><p>Some info...</p></div>
<script>
    $(document).ready(function(){
        $('.myOption').click(function(){
            var $stat = $('#specify')[0].checked;
            if( $stat == true )
                $('.specify').show();
            else
                $('.specify').hide();
        });
    });
</script>

m sure it can be again optimized too..

Upvotes: 1

Michael Copeland
Michael Copeland

Reputation: 849

I think creating a class to hide the <div> is a fairly standard way to approach the problem. Well done! Instead of using the show or hide function on the <div>, it is just as easy to use addClass or removeClass when using the CSS approach. Also, the initial state of the <div> can be shown by using PHP to apply the class if necessary on page load.

<div <? if($thisvolneed=='specify'){echo 'class="specify"';} ?>><p>Some info...</p></div>

Upvotes: 1

Related Questions