简体   繁体   English

单击按钮时如何运行脚本

[英]How to run script when a button is clicked

Hi I'm running a sum and multiplication script for some field input values to a form i made. 嗨,我正在为我制作的表单的某些字段输入值运行求和和乘法脚本。 How can I get this script to run on a button click so that after a user enters a new value they can click a update form button to run the calculations script and update the total sum. 如何使此脚本在单击按钮时运行,以便用户输入新值后,他们可以单击更新表单按钮来运行计算脚本并更新总和。

<script>

var $form = $('#contactForm'),
    $summands = $form.find('.sum1'),
    $sumDisplay = $('#itmttl');

$form.delegate('.sum1', 'change', function ()
{
    var sum = 0;
    $summands.each(function ()
    {
        var value = Number($(this).val());
        if (!isNaN(value)) sum += value;
    });

    $sumDisplay.val(sum);
});




function multiply(one, two) {
  if(one && two){
    this.form.elements.tax.value = one * two;
  } else {
    this.style.color='blue';
  }
}

</script>

Define a function and put the code you want to run inside it. 定义一个函数,然后将要运行的代码放入其中。

var doStuff = function () {
  // do some stuff here
};

Select your button and call that function on click. 选择您的按钮并在单击时调用该函数。 If you're using an A or BUTTON tag you may want to prevent the default action, which I've included in this example. 如果您使用的是ABUTTON标签,则可能要阻止默认操作,此示例中已包含该默认操作。

$('.button').on('click', function (event) {
  doStuff();
  event.preventDefault();
});

This assumes that you're using jQuery 1.7+. 假设您使用的是jQuery 1.7+。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM