Reputation:
What is the correct way of preventing an ajax call if someone where to enter a blank space in an input field?
The code I am trying to do would look something like this (obviously this does not work)
$(document).ready(function() {
$(document).on('click', '#insert_btn', function() {
if ($("#first_name").val().length > 0)) {
$.ajax({
type: 'POST',
url: 'add.php',
datatype: "json",
data: {
first_name: $("#first_name").val(),
last_name: $("#last_name").val(),
position: $("#position").val(),
date: $("#date").val(),
updated: $("#updated").val(),
},
success: function(result) {
if (result == ADD_OK) {
alert('OK')
} else {
alert('wrong');
}
}
})
});
});
Upvotes: 0
Views: 1157
Reputation: 6530
Since you're using jQuery already you can go for something like the code below where I've added the use of jQuery.trim before checking for the length
$(document).ready(function() {
$(document).on('click', '#insert_btn', function () {
// Utilizing https://api.jquery.com/jQuery.trim/
var first_name = $.trim($("#first_name").val());
if (first_name.length > 0) {
$.ajax({
type: 'POST',
url: 'add.php',
datatype: "json",
data: {
first_name: $("#first_name").val(),
last_name: $("#last_name").val(),
position: $("#position").val(),
date: $("#date").val(),
updated: $("#updated").val(),
},
success: function (result) {
if (result == ADD_OK) {
alert('OK')
} else {
alert('wrong');
}
}
})
}
});
});
jQuery.trim(' ') // returns ""
jQuery.trim(' ') // returns ""
jQuery.trim(' this is my search text ') // returns "this is my search text"
Upvotes: 2