2016-03-02 78 views
2

我有一個看起來像這樣 enter image description here如何找出用戶在Javascript中選擇哪個單選按鈕?

眼下一種形式,我遇到的問題是,用戶可以選擇超過1個單選按鈕。他們應該只能夠選擇1. 我有一個JavaScript函數,將通過所有行和禁用這裏看到,沒有選擇按鈕。

function disableNonSelectedRadioButtons(selectedRadioButton) { 
    $('#payer-contract-global-table .clone-target').each(function (i) { 
     var radioName = 'radio' + '-c' + i; 
     if (selectedRadioButton != radioName) 
      $('#' + radioName).prop("checked", false); 
    }); 
} 

This Works。但我需要發送正確的selectedRadioButton到這個功能。我怎樣才能正確地在Javascript中做到這一點?

目前HAML看起來是這樣的:

%input.radio-button{:name => "radio-c#{index}", :type => "radio", :id => "radio-c#{index}", :checked => "true"} 

有沒有在Javascript中某種類型的代碼,我能做到這一點說, 如果我點擊按鈕radio-c2它會發送到我的功能?

+0

爲什麼你不能使用普通的HTML和[給你的單選按鈕同名(http://stackoverflow.com/questions/5419459/how-to-set-that-only-one-radio-button-可待覈查)? –

+0

@ Mdjon26你不清楚你要求什麼,更準確地澄清你的問題。 – divy3993

+0

因爲從你的帖子看來你只想要的是幫助一次只能選擇一個收音機的功能,而不是你需要的javascript。只要做@SébastienVercammen提到。如果這不是你想要的,詳細說明一下。 – divy3993

回答

2

如果遇到該事件沒有被觸發,這是因爲被動態生成的DOM元素(我想...)我解決這個問題是這樣的:

$(document).on('click', 'input[type="radio"]', function(e){ 
    var selectedRadioName = $(this).attr('name'); 
    disableNonSelectedRadioButtons(selectedRadioName); 
}); 

以防萬一。

0

您可以使用prop()

$('input[type="radio"]').click(disableNonSelectedRadioButtons($(this).prop('name'))); 
+0

請勿將Javascript用於HTML作業。 –

+0

雖然專門爲JavaScript提出了問題。 –

3

如果你想使用jQuery:

$('input[type="radio"]').click(function(e){ 
     var selectedRadioName = $(this).attr('name'); 
     disableNonSelectedRadioButtons(selectedRadioName); 
    }); 

如果你動態創建元素,使用事件委派:https://learn.jquery.com/events/event-delegation/

$(document).on('click', 'input[type="radio"]', function(e){ 
     var selectedRadioName = $(this).attr('name'); 
     disableNonSelectedRadioButtons(selectedRadioName); 
}); 

那說,你可以用這個HTML:

<input type="radio" name="giveThemAllTheSameName" /> 

通過給單選按鈕相同的名稱,你將只能選擇一個。

+0

JQuery在控制檯中工作,但在我的應用程序中不起作用。這是爲什麼?我是否需要激活它? – Jay266

+0

請確保您有jQuery的源(或CDN:「https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js」)上面的代碼之前,腳本標記。 您還需要延遲執行,直到DOM加載。即:$(文件)。就緒(函數(){// 上述代碼 }); –

相關問題