Reputation: 980
I have this jQuery that checks if the value of a text field (id_code
) is similar to any of the available values in a select field (id_tipAux
).
The user should not submit a value in the text input (code) similar to a value that already exists in the select field (types).
I am using SweetAlert.
Here is my jQuery code:
$('#frmCreateNew').submit(function(e) {
e.preventDefault(); // I prevent the post to submit before checking it
var codeExists = false;
var types = document.getElementById('id_tipAux');
var code = document.getElementById('id_code').value;
code = code.toUpperCase(); //select vals are all uppercase
console.log('Input : ' + code +);
var i;
for (i = 0; i < types.length; i++){ // iterate all the values of the select field
console.log(types.options[i].value);
if(code == type.options[i].value){ //checks if any of them is equal to the text input value
codeExists = true; //sets the var to true in order to prevent a submit
swal("The code already exists.", "Please type another code", "error");
}
}
if(codeExists == false) { //var is false so it allows to submit
swal("New type created!", {icon: "success",})
.then((value) => {
console.log(value)
$(this).submit() // the form is submitted and the infinite loop starts here
});
}
});
With this jQuery I tried to stop the submit if the user is sending a text input equal to any of the select field options. And it worked, but the problem comes when the user is sending an accepted value, it triggers an infinite loop because of $this.submit()
since the method is waiting for a submit for frmCreateNew
Upvotes: 1
Views: 194
Reputation: 9200
You need to invoke the native form submission rather than the jQuery-wrapped one:
$('#frmCreateNew').submit(function (e) {
e.preventDefault();
var codeExists = false;
var types = document.getElementById('id_tipAux');
var code = document.getElementById('id_code').value;
code = code.toUpperCase(); //select vals are all uppercase
console.log('Input : ' + code + );
var i;
for (i = 0; i < types.length; i++) {
console.log(types.options[i].value);
if (code == type.options[i].value) {
codeExists = true; //sets the var to true in order to prevent a submit
swal("The code already exists.", "Please type another code", "error");
}
}
if (codeExists == false) { //var is false so it allows to submit
swal("New type created!", {
icon: "success",
})
.then((value) => {
console.log(value)
//$(this).submit() // the form is submitted and the infinity loop starts here
// Do this
this.submit();
});
}
});
Upvotes: 3