[英]Set radio button value in javascript
我正在嘗試通過JavaScript設置單選按鈕的值。 但是我不能這樣做。 我試圖做的是有4個單選按鈕,其中一個已被選中。 如果我選擇其他單選按鈕並單擊“刷新”,則應選擇默認單選按鈕。
http://jsfiddle.net/ds345/Un8XK/1/
HTML:
<fieldset data-role="controlgroup" data-type="vertical">
<input type="radio" name="radio" id="x" data-theme="a" />
<label for="x" style="color: White">X</label>
<input type="radio" name="radio" id="y" onclick="axisonoff(this)" data-theme="a" />
<label for="y" style="color: White">Y</label>
<input type="radio" name="radio" id="z" data-theme="a" />
<label for="z" >Z</label>
<input type="radio" name="radio" id="none" data-theme="a" />
<label for="none" style="color: White">None</label>
</fieldset>
<button id = "Refresh" value="Refresh">Refresh</button>
JS:
$(document).ready(function () {
$("#none").attr("checked", true).checkboxradio("refresh"); // if this line is not present initially then it works for the 1st refresh.
});
$("#Refresh").click(function(){
$("#x").attr("checked", false).checkboxradio("refresh");
$("#y").attr("checked", false).checkboxradio("refresh");
$("#z").attr("checked", false).checkboxradio("refresh");
$("#none").attr("checked", true).checkboxradio("refresh");
});
我確信我錯過了一些很小的東西,但無法弄清楚為什么這種方法行不通。
使用的工具:Javascript,Jquery 1.9和JQuery mobile 1.3
謝謝,
Deeksha
處理布爾屬性時,應在attr
使用prop
。
.attr("checked", false)
將把checked="false"
添加到您的元素中。
在HTML中, <input checked="false" .../>
與<input checked="true" .../>
或者只是<input checked .../>
因為該屬性只需要存在於使其處於活動狀態的元素。
請參閱此JSFiddle示例 。
更改代碼以使用.prop()
代替:
$("#none").prop("checked", false)...
這是JSFiddle演示的固定版本: http : //jsfiddle.net/Un8XK/8/
您錯過的是不需要腳本。 只需使用帶有重置按鈕的表單即可:
<form>
<input type="radio" name="radio" value="0" checked>0<br>
<input type="radio" name="radio" value="1">1<br>
<input type="radio" name="radio" value="2">2<br>
<input type="radio" name="radio" value="3">3<br>
<input type="reset">
</form>
如果確實必須使用腳本,則只需在表單中添加一個按鈕,即可將單選按鈕恢復為默認值:
<input type="button" onclick="reset(this.form.radio);" value="Script reset">
和一個功能:
<script>
function reset(els) {
for (var i=0, iLen=els.length; i<iLen; i++) {
els[i].checked = els[i].defaultChecked;
}
}
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.