checked radio button show a div

I have this markup one of my web pages,

<div class="radio-spoof">
    <input type="radio" name="enquiry" value="General enquiry" class="radio"/>
    <div class="checked"></div>
</div>
<label for="general_enquiry">General enquiry</label>
<div class="radio-spoof">
    <input type="radio" name="enquiry" value="Request a brochure" class="radio" checked="true"/>
    <div class="checked"></div>
</div>
<label for="request_a_brochure">Request a brochure</label>

Basically what I am doing is trying to spoof some radio buttons, so I can have good looking ones, when a radio is checked I want to display .checked which is set to display:none by default. I need to check for a checked radio button on DOMReady and when ever a radio is clicked, currently I have this page, but it does not seem to be making the selection of the .checked div correctly.

if($('input[type=radio]:checked')) {
console.log("!");
$(this).parent().children('div').show();
}

I would expect the code above the select the radio buttons parent, and then look for a child div (.checked) and show it. Am I mistaken? `


$(function(){
  $(':radio').change(function(){
    var $this = $(this);
    console.log($this);
    $(':radio[name='+this.name+']').next().hide();
    if($this.is(':checked')){
      $this.next('.checked').show();
    }
  });
});

For above issue, i have done solution on codebins. So, try it on http://codebins.com/codes/home/4ldqpb6

Solution:

$(document).ready(function() {
    $('input[type=radio]').each(function() {
        if ($(this).is(':checked')) {
            $(this).next('.checked').show();
        }
        $(this).click(function() {
            if ($(this).is(':checked')) {
                $(this).next('.checked').show();
            }
        });
    });
});

demo you need to register an event when check box state changes : http://jsfiddle.net/FtPLS/2/ or http://jsfiddle.net/QCkpG/1/

  • Also I reckon you should use .next instead of .children .
  • if you want to hide .checked just do this => $('.checked').hide()
  • you could use $('input[type=radio]').is(':checked') for your check/uncheck condition.
  • Hope this helps the cause, :)

    code

    $(function() {
        // here ==> $('.checked').hide(); will hide all the div with checked class
        $('input').click(function() { // can use .change instead if you want
            if ($('input[type=radio]').is(':checked')) {
                alert('!')
                $(this).parent().next('div').show(); // whatever you wanna show or 
                //$(this).next('div').show();
            }
        });
    });​
    
    链接地址: http://www.djcxy.com/p/56008.html

    上一篇: 根据复选框值创建一个动态链接

    下一篇: 选中单选按钮显示一个div