1

I am trying to set the value of the radio button via javascript. But I am not being able to do so. What I tried to do was have 4 radio buttons one of which is already selected. If I select some other radio button and click on Refresh, default radio button should be selected.

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");
});

I am sure that I have missed something very small but not able to figure out why this approach is not working.

Tools used: Javascript,Jquery 1.9 and JQuery mobile 1.3

Thanks,

Deeksha

4

2 回答 2

5

在处理布尔属性时应该使用propover 。attr

.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/

于 2013-04-17T13:03:01.903 回答
0

您错过的是不需要脚本。只需使用带有重置按钮的表单:

<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>
于 2013-04-17T13:19:48.050 回答