【问题标题】:how to read if radio button checked and save it as 1 with javascript?如果选中单选按钮并使用javascript将其保存为1,如何读取?
【发布时间】:2013-10-02 07:40:39
【问题描述】:

我有 3 个单选按钮:

<div id="step-1">
    <h2 class="StepTitle">
        <label style="font-weight: bold; color: #662819;" id="frage1"></label>
    </h2>
    <br />

    <input type="radio" name="group1" id="antwort1" value="" onmousedown="this.__chk = this.checked" onclick="if (this.__chk) this.checked = false" />
    <label id="antwort1fuerFrage1"></label>
    <br />
    <br />

    <input type="radio" name="group1" id="antwort2" value="" onmousedown="this.__chk = this.checked" onclick="if (this.__chk) this.checked = false" />
    <label id="antwort2fuerFrage1"></label>
    <br />
    <br />

    <input type="radio" name="group1" id="antwort3" value="" onmousedown="this.__chk = this.checked" onclick="if (this.__chk) this.checked = false" />
    <label id="antwort3fuerFrage1"></label>
</div>

我正在尝试读取单选按钮是否被选中,并保存一个值(需要 1 或/0),如下所示:

var frage1 = document.getElementById("frage1").innerHTML;
var antwort1 = document.getElementById("antwort1");
var antwort2 = document.getElementById("antwort2");
var antwort3 = document.getElementById("antwort3");

antwort1 = $('input[id="antwort1"]:checked').val();
antwort2 = $('input[id="antwort2"]:checked').val();
antwort3 = $('input[id="antwort3"]:checked').val();

antwort 1、2、3 未定义。我需要得到01

【问题讨论】:

    标签: javascript jquery radio-button selecteditem radio-group


    【解决方案1】:

    您可以只使用.length,因为您正在查询 ID:

    antwort1 = $('#antwort1:checked').length;
    antwort2 = $('#antwort2:checked').length;
    antwort3 = $('#antwort3:checked').length;
    

    【讨论】:

      【解决方案2】:

      prop()点赞

      antwort1 = $('input[id="antwort1"]').prop();
      antwort2 = $('input[id="antwort2"]').prop();
      antwort3 = $('input[id="antwort3"]').prop();
      

      Fiddle

      【讨论】:

      • 这将始终返回 1,因为即使 jq 空对象是真的
      • @A.Wolff 是正确的,这个答案不会产生正确的结果。示例:jsfiddle.net/VXP5z
      • 更新后的答案仍然错误。建议干脆删掉,有正确答案贴出来。
      【解决方案3】:

      你可以这样做:

      var antwort1 = $('#antwort1:checked').length;
      var antwort2 = $('#antwort2:checked').length;
      
      console.log(antwort1);
      console.log(antwort2);
      

      FIDDLE DEMO

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-08-07
        • 1970-01-01
        • 1970-01-01
        • 2013-11-03
        • 1970-01-01
        • 2013-06-14
        • 1970-01-01
        相关资源
        最近更新 更多