选中HTML复选框后如何调用脚本?

时间:2014-05-08 23:50:25

标签: javascript html forms checkbox

我有以下代码。单击apple时,应调用脚本并弹出警报。为什么这不起作用?

检查apple时,应该调用脚本apple!

<input type="checkbox" name="apple" id="apple" onclick ="apple()" />
<label for = "apple"> Apple ($.59) </label>

2 个答案:

答案 0 :(得分:6)

问题是元素的ID和名称与全局函数相同。元素ID也成为引用元素的全局变量,它们正在替换函数定义。赋予函数不同的名称。

JS:

function appleAlert() {
    var selection = document.getElementById("apple");
    var total = 0;


    if (selection.checked) {
        total = 59;
        alert(total);
    } else {
        alert("Not checked");
    }

}

HTML:

<form name="shopping" action="#" method="post" onsubmit="return appleAlert()">
    <input type="checkbox" name="apple" id="apple" onclick="appleAlert()" />
    <label for="apple">Apple ($.59)</label>
    <input type="checkbox" name="orange" id="apple" onchange="orangeAlert()" />
    <label for="orange">Orange ($.49)</label>
    <input type="checkbox" name="banana" id="apple" onchange="bananaAlert()" />
    <label for="banana">Banana ($.39)</label>
    <input type="submit" value="Submit">
</form>

DEMO

答案 1 :(得分:0)

<div class="col-sm-2 form-inline">
  <label class="switch">Service Type:</label>
</div>
<div class="col-sm-2 form-inline">
  <input type="checkbox" checked name="is_dispatching" value="1"  data- 
    toggle="toggle" data-style="ios" data-on="Dispatching" data-off="Agency">
  <input type="hidden" name="is_dispatching" value="0" data-toggle="toggle" data- 
    style="ios" data-on="Dispatching" data-off="Agency">
</div>

php:

$internal->is_dispatching = $_POST["is_dispatching"];