简体   繁体   中英

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.

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

This assumes that you're using jQuery 1.7+.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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