为什么我的单选按钮实现工作正常

时间:2015-07-20 17:20:46

标签: javascript html

我试图在用户选择任何单选按钮后进行onclick警报。但是,如果用户按下名为ANVIL的单选按钮旁边的任何按钮,则会发送未定义的警报,而如果按下单选按钮名称Anvil,则会发出警告说明铁砧。



K

function processFlow() {

  var tempType;
  for (var i = 0; i < document.flow_form.flow.length; i++) {
    if (document.flow_form.flow[i].checked) {
      tempType = document.flow_form.flow[i].value;
    }
    alert(tempType);
    //document.getElementById("result").innerHTML = document.flow_form.flow[i].value;
    break;
  }

}
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:3)

你的警报()和休息应该在if里面。否则,当他们在第一个项目之后选择任何内容时,它将警告(tempType)未定义,然后中断,这意味着它将永远找不到匹配,因为循环退出。

function processFlow() {

  var tempType;
  for (var i = 0; i < document.flow_form.flow.length; i++) {
    if (document.flow_form.flow[i].checked) {
      tempType = document.flow_form.flow[i].value;
      alert(tempType);
      break;
    }

  }

}

答案 1 :(得分:0)

删除你的循环并使用

document.flow_form.flow.value

&#13;
&#13;
function processFlow() {
  var tempType = document.flow_form.flow.value;
  alert(tempType);
}
[].forEach.call(document.querySelectorAll('input[name="flow"]'), function(inp) {
  inp.onchange = processFlow;
});
&#13;
label { display: block; }
&#13;
<h1>Position Trigger Messages</h1>
<div class="container">
  <div class="sheet_column">
    <form name="flow_form">
      <h2>Flow</h2>
      <label class="flow_row">
        <input type="radio" name="flow" value="anvil" checked>
        ANVIL
      </label>
      <label class="flow_row">
        <input type="radio" name="flow" value="fx">
        FX
      </label>
      <label class="flow_row">
        <input type="radio" name="flow" value="debt">
        Debt
      </label>
      <label class="flow_row">
        <input type="radio" name="flow" value="prms_repos">
        PRMS Repos
      </label>
      <label class="flow_row">
        <input type="radio" name="flow" value="prms_fx">
        PRMS FX
      </label>
      <label class="flow_row">
        <input type="radio" name="flow" value="equity_racs">
        Equity options from RACS
      </label>
      <label class="flow_row">
        <input type="radio" name="flow" value="convertible_bonds">
        Convertible bonds
      </label>
      <label class="flow_row">
        <input type="radio" name="flow" value="firm_derivatives">
        Firm derivatives
      </label>
      <label class="flow_row">
        <input type="radio" name="flow" value="stocks">
        Stocks
      </label>
    </form>
  </div>
</div>
&#13;
&#13;
&#13;