如何将单选按钮的名称传递给onclick事件的javascript?

时间:2012-12-23 20:42:20

标签: php javascript-events onclick radio-button alert

我有一个包含n行的html表。每行都有一个名称和2个单选按钮。如果我单击一个单选按钮,我想显示一个说明投票数的警报。我应该如何将单选按钮的名称传递给javascript,我应该如何进行计数?提前谢谢。

这是php部分:

list($cols,) = $xlsx->dimension();
$var=0;
foreach( $xlsx->rows() as $k => $r) {
    $var++;
    echo '<tr>';
        echo '<td>'.$k.'</td>';
        echo '<td>'.( (isset($r[0])) ? $r[0] : '&nbsp;' ).'</td>';
        echo '<td><Input type = "Radio" Name ="vote'.$var.'" value= "pacada"  onclick = "AddPacada()"></td>';
        echo '<td><Input type = "Radio" Name ="vote'.$var.'" value= "toledo"  onclick = "AddToledo()"></td>';
    echo '</tr>';

这是javascript部分

function AddPacada(){
if(document.tally.pacada.checked == true){
    alert("You have clicked on Pacada.");
}
}function AddToledo(){
if(document.tally.toledo.checked == true){
    alert("You have clicked on Toledo.");
}
}

2 个答案:

答案 0 :(得分:1)

您只需将其作为参数传递:

... onclick = "AddPacada(this)" ...
                         ^^^^

/* And in your function: */

function AddPacada(radio) {
    alert(radio.value);
}

答案 1 :(得分:0)

将PHP代码中的onclick更改为onclick=tally(this)

然后,此javascript将提醒当前所选的总计:

<script>
  var selections = new Array(); //keep track of the selections
  function tally(e) {
    val  = e.value;
    name = e.name;

    selections[name] = val;  //an associative array or "hash"

    var totals = new Array();
    for (var key in selections) {
      var selection=selections[key];
      if(totals[selection] == undefined) { //set to 1 if not already initialized
        totals[selection] = 1;
      } else {
        totals[selection] += 1;
      }
    }
    alert(val + " has been selected " + totals[val] + " times");
  }

</script>

样式方面,我会尝试发出以下HTML:

<input type="radio" name="var1" value="a" onclick="tally(this)"/>
<input type="radio" name="var1" value="b" onclick="tally(this)"/>

<input type="radio" name="var2" value="a" onclick="tally(this)"/>
<input type="radio" name="var2" value="b" onclick="tally(this)"/>

注意间距和大小写。