【问题标题】:How do I call a script when a HTML checkbox is checked?选中 HTML 复选框时如何调用脚本?
【发布时间】:2018-12-12 16:13:06
【问题描述】:

我有以下代码。当你点击苹果时,应该调用一个脚本并弹出一个警报。为什么这不起作用?

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

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

【问题讨论】:

  • Javascript 控制台中是否有任何错误?

标签: javascript html forms checkbox


【解决方案1】:

问题在于元素的 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

【讨论】:

    【解决方案2】:
    <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"];
    

    【讨论】:

    • 我试过了,但它不起作用,我想从切换复选框向 is_dispatching 发布值
    • 如果选中 1 else 0....但我希望首先选中复选框,值为 1....我该怎么做?
    猜你喜欢
    • 2021-11-09
    • 2023-03-31
    • 1970-01-01
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    • 2013-06-21
    相关资源
    最近更新 更多