[英]Dynamically hide/show radio buttons in rails form doesn't hide when unchecked
當選中“每日”單選按鈕時,我需要以滑軌形式動態顯示/隱藏單選按鈕列表。 這幾乎可行,除了當我選中“每周”(取消選中“每日”)時,列表不會隱藏。 javascript的新手,試圖弄清楚我所缺少的內容。
<%= form_for list_chores_path(@list.id) do |f| %>
<div class="field">
<%= f.radio_button :frequency, 'Daily', onClick: "resetradio(this)" %> Daily<br>
<div class="buttons" style="display:none;">
<%= f.radio_button :time_of_day, 'Morning', onClick:"setradio()" %> Morning<br>
<%= f.radio_button :time_of_day, 'Evening', onClick:"setradio()" %> Evening<br>
<%= f.radio_button :time_of_day, 'Any Time', onClick:"setradio()" %> Any Time<br>
</div>
<%= f.radio_button :frequency, 'Weekly' %> Weekly<br>
</div>
<script type="text/javascript">
function resetradio (radio) {
var buttons = document.querySelector('.buttons');
var radios = document.getElementsByName('/lists/<%= @list.id %>/chores[time_of_day]');
radios[0].checked = false;
if (radio.checked == true) {
buttons.style.display = 'block';
}
else {
buttons.style.display = 'none';
}
}
function setradio () {
var radio = document.getElementsByName('/lists/<%= @list.id %>/chores[frequency]')[0];
if (radio.checked == false) {
radio.checked = true;
}
}
</script>
這是HTML
<div class="field">
<input onclick="resetradio(this)" type="radio" value="Daily" name="/lists/4/chores[frequency]" id="_lists_4_chores_frequency_daily"> Daily<br>
<div class="buttons" style="display: block;">
<input onclick="setradio()" type="radio" value="Morning" name="/lists/4/chores[time_of_day]" id="_lists_4_chores_time_of_day_morning"> Morning<br>
<input onclick="setradio()" type="radio" value="Evening" name="/lists/4/chores[time_of_day]" id="_lists_4_chores_time_of_day_evening"> Evening<br>
<input onclick="setradio()" type="radio" value="Any Time" name="/lists/4/chores[time_of_day]" id="_lists_4_chores_time_of_day_any_time"> Any Time<br>
</div>
<input type="radio" value="Weekly" name="/lists/4/chores[frequency]" id="_lists_4_chores_frequency_weekly"> Weekly<br>
這是因為當您單擊每周時不會調用javascript函數-resetradio(this)。 以下應該工作
<%= f.radio_button :frequency, 'Weekly', onClick: "resetradio(this)" %> Weekly<br>
我通過將Onclick添加到Weekly(Thanks Shani!),然后在resetradio()函數中創建單選變量而不是將“ this”傳遞給它來修復它。
<script type="text/javascript">
function resetradio () {
var radio = document.getElementsByName('/lists/<%= @list.id %>/chores[frequency]')[0];
var buttons = document.querySelector('.buttons');
var radios = document.getElementsByName('/lists/<%= @list.id %>/chores[time_of_day]');
radios[0].checked = false;
if (radio.checked == true) {
buttons.style.display = 'block';
}
else {
buttons.style.display = 'none';
}
}
function setradio () {
var radio = document.getElementsByName('/lists/<%= @list.id %>/chores[frequency]')[0];
if (radio.checked == false) {
radio.checked = true;
}
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.