2013-03-29 35 views
1

我試圖編寫jquery/JS邏輯隱藏/顯示說明基於單選按鈕被檢查與否。如果單選按鈕在頁面加載時被選中,我想要加載與該單選按鈕相關的描述。但默認的任一個必須選擇/檢查jquery/javascript單選按鈕隱藏/顯示頁面加載屬性的邏輯

我曾嘗試使用.change編譯並點擊ready()內部的方法。但沒有成功

我只有兩個單選按鈕,我不是一個JavaScript/jQuery的人。任何輸入讚賞。這是一個例子

<div id="ServiceSelection">  
<input type="radio" name="Service" checked="Checked" value="B"> Option 1 
    <br> 
<input type="radio" name="Service" value="P"> Option 2 
    <br> 
    <div id="DivB" style="display:none" class="desc">B Description goes here </div> 
<div id="DivP" style="display:none" class="desc">P Description goes here </div>  
</div> 

被修改DIV:預先

<div id="ServiceSelection">  
<input type="radio" name="Service" checked="Checked" value="B"> Option 1 
<br> 
<div id="DivB" style="display:none" class="desc">B Description goes here </div> 
<input type="radio" name="Service" value="P"> Option 2 
<br> 
<div id="DivP" style="display:none" class="desc">P Description goes here </div>  
</div> 

由於Ĵ

回答

1

嘗試這種情況:

function ShowData(evt) { 
    var val = $("input[name=Service]:checked").val(); 
    if (val == 'B') { 
     $('#DivB').show(); 
     $('#DivP').hide(); 
    } else { 
     $('#DivP').show(); 
     $('#DivB').hide(); 
    } 
} 

$('input[name=Service]:radio').change(ShowData); 
ShowData(); 

DEMO HERE

+0

感謝您的輸入......我嘗試了這個新的DIV我剛發佈。當我在小提琴上演示但在實際頁面上演示時它工作正常,我應該將它包裝在document.load方法中嗎?或者其他一些方法? @ will.i.am – Jauyzed

2
if($('input[name=Service]').is(':checked')){ //is it checked? 
    var v = $('input[name=Service]:checked').val(); //get the value 
    $('div[id$='+v+']').show(); //target the end of selector, and match it to our value 
} 

$('input[name=Service]').on('click', function(){ 
    $(this).parent().find('div').hide(); //hide the divs... 
    $('div[id$='+$(this).val()+']').show(); //show the div based on our value again.. 
});  

fiddle

+0

感謝您的意見。我用剛剛發佈的新DIV嘗試了這一點。當我在小提琴上演示但在實際頁面上演示時它工作正常,我應該將它包裝在document.load方法中嗎?我做了。在頁面加載時,我看到第一個選項,但是當我單擊/更改選項時,我沒有看到第二個測試顯示出來......可能是什麼問題? @Ohgodwhy – Jauyzed

+0

對不起,沒有測試..「*文本」 – Jauyzed

1

我建議:

// hide the div elements with JavaScript, so they're visible to those 
// users with JavaScript disabled: 
$('#ServiceSelection div[id]').hide(); 

// select the radio input elements and bind to the change event 
$('input:radio').change(function(){ 
    // find the element whose id is equal to 'Div' + the value of the radio, 
    // show that div, hide the sibling div elements 
    $('#Div' + this.value).show().siblings('div').hide(); 
// filter the radio elements to find the one that's checked, and trigger the change event 
}).filter(function(){return this.checked; }).change(); 

JS Fiddle demo

參考文獻:

+0

感謝您輸入@大衛托馬斯。但實際的頁面已經啓用了JS,這是一個JSP。我是否應該圍繞上述解決方案包裝您建議的代碼? – Jauyzed