How to run script when a button is clicked

廉价感情. 提交于 2019-12-13 04:52:48

问题


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>

回答1:


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.

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

This assumes that you're using jQuery 1.7+.



来源:https://stackoverflow.com/questions/27180712/how-to-run-script-when-a-button-is-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!