0

I have a couple of buttons on my form that do mileage calculations and the other updates the cost. These work as expected but they also submit the form.

Here are the fields:

 @Html.EditorFor(model => model.Miles, new { htmlAttributes = new { @class = "form-control", @id = "number" } })
     <button onclick="roundTrip()">Round Trip?</button>&nbsp;
     <button onclick="updatedPrice()">Update Price</button>

 @Html.EditorFor(model => model.Cost, new { htmlAttributes = new { @class = "form-control", @id = "price" } })

Here is my JavaScript:

    function updatedPrice() {
        var price = $("#number").val() * @calcMiles;
        var calPrice = price.toFixed(2)
        $("#price").val(calPrice);
    }

    function roundTrip() {
        var calc = $("#number").val() * 2;
        $("#number").val(calc);
    }

Maybe I need to do a replace? Not sure why it submits when I click either one of these.

Thanks for your help!

Scott Purtan
  • 237
  • 1
  • 10
  • for this to be a question, there should still be a form to be deactivated here https://stackoverflow.com/help/how-to-ask – Mister Jojo Sep 08 '21 at 23:16
  • You can just not put them inside a
    . However if you want the user to be able to submit the form, you can either add `type="button"` to the button or assign the event handler with JS/jQuery instead of an inline `onclick` (which is bad practice anyway). Like `$('#btnTrip').on('click', function (e) { e.preventDefault(); /* price calculation here */ });`
    –  Sep 08 '21 at 23:19
  • 1
    Duplicate: [How to prevent buttons from submitting forms](https://stackoverflow.com/questions/932653/how-to-prevent-buttons-from-submitting-forms) –  Sep 08 '21 at 23:20

0 Answers0