2012-09-05 46 views
0

我試圖讓this page上的網址字段僅在上一個問題的單選按鈕選擇「是」時顯示。我搜索並嘗試了幾個代碼示例,但它們不起作用。有沒有人對我有任何建議?如果選擇了單選按鈕,則顯示字段

在此先感謝!

<div class="editfield"> 
<div class="radio"> 
    <span class="label">Do you have your own website? (required)</span> 
    <div id="field_8"><label><input type="radio" name="field_8" id="option_9" value="Yes"> Yes</label><label><input type="radio" name="field_8" id="option_10" value="No"> No</label></div> 
</div> 
</div> 

<div class="editfield"> 
<label for="field_19">Website URL </label> 
<input type="text" name="field_19" id="field_19" value="" /> 
</div> 
+4

請出示你的問題以及相應的HTML和JavaScript。 –

+0

我也注意到你可以在你的問題中使用jQuery,這在那裏也可以嗎? –

+0

我已更新原始帖子,以包含用於字段的HTML。是的,jQuery在這裏也是可用的。 – Mitchell

回答

2

我注意到你初始時把我給你的javascript放在頁面頂部。如果你打算這樣做,那麼你需要將代碼封裝在jquery $(document).ready(function(){ });中。您只需要在HTML之後使用javascript時準備好文檔。

$(function() { 
    // place code here 
}); 

然而,在這種情況下我創造了另一種替代方案,會更好,但不要忘記,你必須初始設置該網頁的網址格爲隱藏。另外,我強烈建議您設置更好的控制ID;它會讓你的javascript更容易理解。

$('input[name=field_8]').on("click", function(){ 
    var $div_WebUrl = $('#field_19').closest('.editfield'); 

    if($('input[name=field_8]').index(this) == 0) 
     $div_WebUrl.show(); 
    else 
     $div_WebUrl.hide(); 
});​ 

Live DEMO

+0

謝謝!我已經在網站上安裝了代碼,但沒有奏效。想知道我是否做錯了什麼。你能看看嗎? http://myfrugaltech.com/dev/savoo/register/ – Mitchell

+0

@MitchellWischmann首先,你需要讓div包含最初通過display:none隱藏的網址,如我的演示所示。 –

+0

@MitchellWischmann我已根據我在您的網站上看到的內容更新了我的答案。 –

1

我創建了一個小例子:

<div class="editfield"> 
<div class="radio"> 
    <span class="label">Do you have your own website? (required)</span> 
    <div id="field_8"><label><input type="radio" name="field_8" id="option_9" value="Yes" onclick="document.getElementById('divUrl').style.display='block'"> Yes</label><label><input type="radio" name="field_8" id="option_10" value="No" onclick="document.getElementById('divUrl').style.display='none'"> No</label></div> 
</div> 
</div> 

<div class="editfield" id="divUrl" style="display:none"> 
<label for="field_19">Website URL </label> 
<input type="text" name="field_19" id="field_19" value="" /> 
</div>​ 

的jsfiddle:http://jsfiddle.net/EQkzE/

注:我已經更新了div來包括一種風格,因爲我不知道你的CSS類是什麼樣的。祝你好運。

+0

感謝您設置小提琴頁面,我使用它。 – Swards

0

這裏是一個純粹的JS解決方案:

document.getElementById("field_19").parentNode.style.display = "none"; 
document.getElementById("option_9").onclick = toggleURLInput; 
document.getElementById("option_10").onclick = toggleURLInput; 

function toggleURLInput(){ 
    document.getElementById("field_19").parentNode.style.display = (document.getElementById("option_9").checked)? "block" : "none"; 
} 

不是一個非常動態的解決方案,但it works

0

像這樣的東西會將click事件綁定到一個簡單的函數來查看單選按鈕並顯示其他div。

$('#option_9').on('click', function() { 
    if ($('#option_9').is(':checked')) { 
    $('#field_19').closest('.editfield').show(); 
    } else { 
    $('#field_19').closest('.editfield').hide(); 
    } 
}); 

Run sample code

+0

就這樣,你知道,生活已被棄用,並已被取代。 –

+0

謝謝 - 我已經更新了它。 – Swards

相關問題