Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
16
rated 0 times [  23] [ 7]  / answers: 1 / hits: 15880  / 8 Years ago, sun, january 31, 2016, 12:00:00

I have a bootstrap modal. When the user clicks the Update button it makes an ajax call to update the DB. However if the update fails for some reason I want to display the error message and leave the modal open.



Everything appears to be working in the order I expect, however the e.preventDefault() doesn't appear to stop the modal from closing.



Why is the preventDefault() not stopping the button from submitting?



My button:



<button type=submit class=btn btn-success id=btnUpdate style=margin-right:10px>Update</button>


Javascript button click code.



$(#btnUpdate).on(click, function (e) {
// reset the message...
$(#errorMessage).html();

// get the value...
var myParam = $(#someSelection).attr(someData);
var myParamData = JSON.parse(myParam );

updateData(myParamData.Name)
.done(function (result) {
if (!result.d == ) {
$(#errorMessage).html(result.d);
e.preventDefault();
}
else {
loadData();
}
});
});

More From » jquery

 Answers
214

Just change the type of the button to button will prevent the submit :



<button type=button class=btn btn-success id=btnUpdate style=margin-right:10px>Update</button>


Hope this helps.






Update :



To profit from HTML5 validation when you're using submition by ajax you could use checkValidity() method.




The HTMLSelectElement.checkValidity() method checks whether the element has any constraints and whether it satisfies them. If the element fails its constraints, the browser fires a cancelable invalid event at the element, and then returns false.




So your code will be :



$(#btnUpdate).on(click, function (e) {
// reset the message...
$(#errorMessage).html();

if($(form)[0].checkValidity()) {
// get the value...
var myParam = $(#someSelection).attr(someData);
var myParamData = JSON.parse(myParam );

updateData(myParamData.Name)
.done(function (result) {
if (!result.d == ) {
$(#errorMessage).html(result.d);
e.preventDefault();
}
else {
loadData();
}
});
}else{
console.log(invalid form);
}
});

[#63493] Thursday, January 28, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marcos

Total Points: 331
Total Questions: 106
Total Answers: 104

Location: Gabon
Member since Sat, Jul 25, 2020
4 Years ago
;