0

I have a button inside a form in asp.net core. The form has it's own submit button which is supposed to trigger the create action when it is clicked. I have another button insde the form which is just calling a piece of javascript code. I don't understand why when I click on the button to call the javascript, the post action "Create" is called also afterwards. That is I see the alert box and then I get redirected by the action. I just want to display the alert without this triggering the action method.

function ValidateName() {
  var name = document.getElementById('btnName').value;
  alert(name);

}
<form asp-action="Create">
  <div class="form-group">

    <div class="form-group">
      <label asp-for="Name" class="control-label"></label>
      <input asp-for="Name" class="form-control" />
      <span asp-validation-for="Name" class="text-danger"></span>
    </div>
    <div class="row">
      <div class="col-md-6 text-center">
        <button id="btnName" class="btn btn-primary btn-md center-block" Style="width: 150px;" OnClick="ValidateName()">Validate</button>
      </div>
    </div>
  </div>

  <div class="form-group">
    <input type="submit" value="Créer" class="btn btn-default" />
  </div>
</form>
Eddie
  • 26,593
  • 6
  • 36
  • 58
TropicalViking
  • 407
  • 2
  • 9
  • 25

1 Answers1

0

you need to prevent the default behavior

function ValidateName(e) {
    e.preventDefault();
    var name= document.getElementById('btnName').value;
    alert(name);

}
bill.gates
  • 14,145
  • 3
  • 19
  • 47