Validate form with JS [closed]

0

I want to validate a form with js through an alert

My code is the following but it is not working for me

I have removed the type="submit" from the button, otherwise, it always confirms the form

function security(){
  var mensaje = confirm("¿Estás seguro de que quieres BORRAR este aviso?");
if (mensaje) {
  var theForm = document.forms['formborrar'];
  theForm.submit();
}
else {
}
}
<form action="borrar.php" method="post" name="formborrar">
  <input type="text" name="id" value="<?php echo $id; ?>" style="display: none;">
  <input class="btn" onclick="security()" type="submit" value="Borrar Aviso" name="submit">
</form>
    
asked by Tefef 11.10.2018 в 10:01
source

1 answer

1

Now it is clearer what you want to achieve.

The problem that you seem to have, is that you have a input with type="submit" . This type what it does is always call the action of the form when you click , so by much validation that you are putting it in your JS function will continue to be sent. If you change a couple of things in the HTML and another in the JS , you should work.

HTML

<form action="borrar.php" method="post" name="formborrar">
  <input type="text" name="id" value="<?php echo $id; ?>" style="display: none;">
  <input class="btn" onclick="security()" value="Borrar Aviso" name="submit">
</form>

JS

function security(){
  var mensaje = confirm("¿Estás seguro de que quieres BORRAR este aviso?");
if (mensaje) {
  alert('SI');
  document.forms.namedItem('formborrar').submit();
}
else {
  alert('NO');
}
}

Try and tell us

EDIT

The alert can be removed. I left them to see that the condition of if is working correctly.

    
answered by 11.10.2018 в 11:47