2014-01-16 77 views
44

出於某種原因,我似乎無法弄清楚這一點。使用javascript檢查單選按鈕

我在HTML中切換類別的一些單選按鈕:

<input type="radio" name="main-categories" id="_1234" value="1234" /> // All 
<input type="radio" name="main-categories" id="_2345" value="2345" /> // Certain category 
<input type="radio" name="main-categories" id="_3456" value="3456" /> // Certain category 
<input type="radio" name="main-categories" id="_4567" value="4567" /> // Certain category 

用戶可以選擇任何他/她想要的,但是當某些事件觸發,我想設置1234被設置檢查電臺按鈕,因爲這是默認選中的單選按鈕。

我已經試過這(有和沒有jQuery的)版本:

document.getElementById('#_1234').checked = true;

但它似乎並沒有更新。我需要它可見地更新,以便用戶可以看到它。 任何人都可以幫忙嗎?

編輯:我只是累了,忽略了#,謝謝你指出,那和$.prop()

+0

檢查這個StackOverflow的問題:如何檢查與jQuery單選按鈕] [1] [1]:http://stackoverflow.com/questions/5665915/how-to-check-a-radio -button-with-jquery –

+5

改爲'document.getElementById('_ 1234')。checked = true;' – stackErr

+1

@stackErr without'#' –

回答

81

不要用本地JS混合CSS語法(#的標識符)

本地JS的解決方案:

document.getElementById("_1234").checked = true;

JQuery的解決方案:

$("#_1234").prop("checked", true);

+1

從技術上講,它是CSS選擇器語法。 jQuery只是借來並擴展它 –

+0

謝謝,@TimSeguine – zavg

+0

jQuery從'querySelector'得到它我想象中。 – Andy

11

如果你想設置的「1234」按鈕,你需要使用它的「身份證」:

document.getElementById("_1234").checked = true; 

當你使用瀏覽器API(「的getElementById」),您不使用選擇器語法;你只需傳遞你正在尋找的實際「id」值。您在jQuery或.querySelector().querySelectorAll()中使用選擇器語法。

+1

對不起,只是一個錯誤的複製粘貼。現在更新。 – ptf

1

通過使用document.getElementById()函數,您不必在元素的id之前傳遞#

代碼:

document.getElementById('_1234').checked = true; 

演示: JSFiddle

6

最簡單的方法很可能是使用jQuery,如下:

$(document).ready(function(){ 
    $("#_1234").attr("checked","checked"); 
}) 

這增加了一個新屬性 「檢查」(在HTML不需要值)。 只記得包括jQuery庫:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
5

今天,在2016年,它是保存使用document.querySelector不知道ID(特別是如果你有超過2個單選按鈕):

document.querySelector("input[name=main-categories]:checked").value