@hubman answering your question: How can I ask before sending?
Canceling the submission of a form can be done in several ways, it all depends on which way you want to use.
- Prevent the execution of the form by capturing the input / button click with submit type and using preventDefault.
function enviar() {
alert('enviado');
}
function preguntar(event) {
var opcion = confirm("Desea enviar el formulario");
if(!opcion) {
event.preventDefault();
}
}
<form action="javascript: enviar()">
<button type="submit" onclick="preguntar(event)">
Enviar
</button>
</form>
Note : This method is failing because it does not capture other events such as keyDown
if the user presses the Enter
key.
- Remove the action attribute of the form to avoid accidental shipments
function enviar(){
var opcion = confirm('Desea enviar el formulario ?');
if(opcion) {
alert('Enviado');
}
}
<form>
<button onclick="enviar()">
Enviar
</button>
</form>
Note Although this solution becomes more elegant, more knowledge is needed to send the form. Either by AJAX capturing the values of the form or by including the attribute action
by javascript and launching the envento submit
later.
Going back to your example would be the option to execute it in the onclick
and do the validation in the onsubmit
and in fact it is correct to do it there. What fails is not the logic of asking or validating if not using the sweet library.
function esNumero(value) {
return value / value === 1;
}
function validar(event, form) {
var inputs = $(form).serializeArray();
var numero = inputs.find(input => input.name === 'numero' );
return esNumero(numero.value); // && otras validaciones;
}
function preguntar(event) {
event.preventDefault();
swal({
title: "Are you sure?",
text: "You will not be able to recover this imaginary file!",
icon: "warning",
buttons: {
cancel: {
text: "Cancel",
value: null,
visible: true,
className: "",
closeModal: true,
},
confirm: {
text: "Yes, delete it!",
value: true,
visible: true,
className: "",
closeModal: true
}
}
}).then(function(value) {
var form = $('#miFormulario');
if (value) form.submit();
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
<form action="javascript: alert('Enviado')" method="post" onsubmit="validar(event, this)" id="miFormulario">
<label>Numero</label>
<input type="text" name="numero" />
<!-- type como button y no como submit -->
<input type="button" onclick="preguntar(event)" value="Enviar" />
</form>
There were several errors, since they had changed the API with the latest versions.
This happens because you use the CDN link to the latest version and not a specific version.