2014-05-07 46 views
1

請看到這一點:http://gisdev.clemson.edu/fireflies使複選框表現得像單選按鈕

接近右上方的三個複選框,我試圖讓他們像單選按鈕的工作。部分編程正在工作,但這裏有些問題:

最初,'縣'複選框被選中。如果我點擊'Hydric Soil Rating'複選框,然後點擊Counties複選框,Hydric複選框仍然保持選中狀態。控制檯不輸出任何內容,這意味着當問題發生時,變量的值會丟失。

下面是相關代碼:

var checkboxescontainer = document.querySelectorAll('.leaflet-control-layers-overlays'); 
var checkboxes_controls = checkboxescontainer[0].children; 

$(checkboxes_controls).each(function() 
{ 
    console.log($.trim($(this).text())); 
    if (eventtype === 'add') 
    { 
     if (layername === $.trim($(this).text())) 
     { 
      // don't do anything but uncheck all others--making them work like radio buttons 
     } 
     else 
     { 
      $(this).find('input:checkbox').attr('checked', false); 
     } 
    } 
}); 

任何想法?

編輯我看到問題:第二次點擊Counties圖層來選擇它甚至沒有激發圖層「添加」事件,因爲我只是將圖層前後發送。 Hmmmm。

+0

什麼'eventtype'和'layername'應該是?請發佈完整的相關代碼(包括HTML) – Ejaz

+0

我發佈了一個'編輯';請看看。我的問題是,圖層並沒有真正被刪除。謝謝。 – IrfanClemson

+0

你爲什麼不使用單選按鈕?我會說使用複選框作爲單選按鈕是糟糕的用戶界面。 –

回答

6

這裏的關鍵問題是,你需要將一組的箱子,然後如果單擊組中的任何一個,通過設置迭代,取消選中所有除被點擊的一個。

您可以使用類名進行分組。然後給每個ID。

點擊該類後,保存點擊的ID。然後遍歷類中的複選框並取消選中與保存的ID不同的任何ID。

<form action=""> 
    <input id="cbBike" type="checkbox" class="CB2RBVehicles" name="vehicle" value="Bike" checked>I have a bike<br /> 
    <input id="cbCar" type="checkbox" class="CB2RBVehicles" name="vehicle" value="Car">I have a car<br /> 
    <input id="cbBoth" type="checkbox" class="CB2RBVehicles" name="vehicle" value="Both">I have both<br /> 
    <input id="cbNeither" type="checkbox" class="CB2RBVehicles" name="vehicle" value="Neither">I have neither<br /> 
</form> 


var selectedBox = null; 

$(document).ready(function() { 
    $(".CB2RBVehicles").click(function() { 
     selectedBox = this.id; 

     $(".CB2RBVehicles").each(function() { 
      if (this.id == selectedBox) 
      { 
       this.checked = true; 
      } 
      else 
      { 
       this.checked = false; 
      };   
     }); 
    });  
}); 

Here's an example

+0

非常感謝。我相信你的答案,就像上面接受的來自chep263的答案一樣。實際上,我在問題中的原始代碼也是如此。我的問題中的'問題'是我沒有從地圖上「移除」圖層,只是將它們往返發送。所以檢查/取消選中不會觸發我的代碼中的功能。我的問題已修復,可在頁面中看到。再次感謝! – IrfanClemson

3

如果您希望複選框充當單選按鈕,請將onClick事件偵聽器附加到所有複選框,移除「checked」屬性並將其放置在被單擊的位置上。

checkboxes_controls = jQuery(document.querySelectorAll('.leaflet-control-layers-overlays input[type=checkbox]')) 

jQuery(checkboxes_controls).click(function(){ 
    jQuery(checkboxes_controls).removeAttr('checked'); 
    jQuery(this).attr('checked', 'checked'); 
}); 
+0

您的回答是有效的!需要進行小幅編輯,現在在頁面上。謝謝一堆!這是另一回事,我仍然有層不正常的問題,但複選框現在像單選按鈕一樣工作。謝謝! – IrfanClemson