2012-06-14 41 views
0

如果你不介意的話,幫助不大。jQuery顯示/隱藏單選按鈕更改頁面加載

基本上,我有3個收音機和一個div。當第三個單選框被選中時,div應該可見。但是,當頁面加載時可以檢查廣播框,因此如果選中第三個框,則需要顯示div,否則應該最初隱藏,但如果稍後檢查第三個框,則可以看到它。

HTML:

<input type="radio" name="image_location" value="featured_image" /> 
<input type="radio" name="image_location" value="all_images" /> 
<input type="radio" name="image_location" value="custom_field" /> 

<div id="image_location_custom_field"> 
    ** Content ** 
</div> 

在那裏我已經使用JavaScript走到這一步:

jQuery('input[name=image_location]').hide(); 
jQuery('input[name=image_location]').change(function() { 
    var selected = jQuery(this).val(); 
    if(selected == 'custom_field'){ 
     jQuery('#caption_custom_field').show(); 
    } else { 
     jQuery('#caption_custom_field').hide(); 
    } 
}); 

非常感謝

回答

4

只是檢查單選按鈕被選中的秀格,你也可以使用CSS來隱藏DIV

<input type="radio" name="image_location" value="featured_image" /> 
<input type="radio" name="image_location" value="all_images" /> 
<input type="radio" name="image_location" value="custom_field" /> 

<div style="display:none" id="image_location_custom_field"> 
    ** Content ** 
</div>​ 
//on dom ready 
if (jQuery('input[value=custom_field]:checked').length > 0){ 
    jQuery('#image_location_custom_field').show() 
} 
else { 
    jQuery('#image_location_custom_field').hide(); 
} 
jQuery('input[name=image_location]').change(function() { 
    var selected = jQuery(this).val();console.log(selected); 
    if(selected == 'custom_field'){ 
     jQuery('#image_location_custom_field').show(); 
    } else { 
     jQuery('#image_location_custom_field').hide(); 
    } 
}); 

W/O檢查FIDDLE
與檢查FIDDLE

+0

謝謝,工作得很好。 – OzTheGreat

1

隱藏<div>與初始頁面加載CSS - http://jsfiddle.net/yh5ct/

$("input[type=radio]").on("click", function() { 
    if ($(this).val() == "custom_field") { 
     $("div").show(); 
    } else { 
     $("div").hide();   
    } 
});​ 
0

我會嘗試像這個:

jQuery.noConflict(); 

(function($) { 
    $(document).ready(function() { 
    $(':radio[name="image_location"]').on('change', function() { 
     if ($(this).val() == 'custom_field') { 
     $('#caption_custom_field').show(); 
     } else { 
     $('#caption_custom_field').hide(); 
     } 
    }).last().trigger('change'); // This triggers the event for the last element. 
    }); 
})(jQuery);