簡體   English   中英

Javascript或JQuery:單擊radiobutton

[英]Javascript or JQuery: click a radiobutton

http://jsfiddle.net/tearex/untbe/

<body style="text-align:center">
  <a>
   HOW TO check a button
  </a>
       <fieldset data-role="controlgroup" data-type="horizontal"  >
 <input name="btn1" id="a1" type="radio" value="1"  />
            <label for="a1">1 populate USA</label>
            <input name="btn1" id="a2" type="radio"  />
            <label for="a2" class="bigga">2 populate Germany</label>

    </fieldset>

如何選擇按鈕?

document.getElementById('a2').attr('checked', 'checked')

jQuery("#a2").attr('checked', true);
jQuery("input[value='1']").attr('checked', true);
jQuery('input:radio[name="type"]').filter('[value="1"]').attr('checked', true);

我已經嘗試了在其他線程中找到的所有方法,但沒有一個可行。

你需要使用jQuery包裝器來使用像.attr()這樣的方法,但要設置你需要使用的checked屬性.prop()

$('#a2').prop('checked', true);
$y('input[name="type"][value="1"]').prop('checked', true);

使用vanila javascript

document.getElementById('a2').checked = true

在一般意義上,如果您直接引用DOM元素,則只需設置.checked屬性:

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

...或者如果您使用的是jQuery,請使用.prop()方法:

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

但是,我在你的小提琴中注意到你正在使用jQuery mobile,它增加了特殊的樣式,並且顯示給用戶的元素不是實際的單選按鈕元素。 對於這種情況,正如jQuery移動單選按鈕doco頁面底部所解釋的,如果你用JS設置了檢查狀態,那么你需要調用.checkboxradio("refresh")告訴jQuery mobile更新顯示:

$("#a2").prop("checked", true).checkboxradio("refresh");

演示: http//jsfiddle.net/untbe/1/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM