Reputation: 2141
I'm sending data to my database using .ajax. I've got two fields. I'd like to check if either are empty and if so display an error. The first if works fine. That message display, but the else if doesn't display. What could be my problem? I'm not too familiar with javascript and iquery.
$.ajax({
type: "POST",
url: "submit.php",
data: data,
cache: false,
beforeSend: function() {
if (!$.trim($("#cat").val())) {
$(".fb-error").css( "display", "block" );
$(".fb-error").html("<p>the cat field is empty</p>");
xhr.abort();
}
else if (!$.trim($("#box").val())) {
$(".fb-error").css( "display", "block" );
$(".fb-error").html("<p>the box field is empty</p>");
xhr.abort();
}
},
success: function(html){
$('textarea#box').val('');
$("#box-wrap").prepend(html);
}
});
Upvotes: 0
Views: 207
Reputation: 319
I'd put the errors in an array, and display them if it's not empty
var errors = [];
if (!$.trim($("#cat").val())) {
errors.push("<p>the cat field is empty</p>");
}
if (!$.trim($("#box").val())) {
errors.push("<p>the box field is empty</p>");
}
if(errors.length){
$(".fb-error").css( "display", "block" ).html(errors.join(''));
xhr.abort();
}
Upvotes: 2
Reputation: 166
Consolidate:
var error = false;
if (!$.trim($("#cat").val())) {
$(".fb-error").append("<p>the cat field is empty</p>");
error = true;
}
if (!$.trim($("#box").val())) {
$(".fb-error").append("<p>the box field is empty</p>");
error = true;
}
if (error) {
xhr.abort();
$(".fb-error").css( "display", "block" );
}
Upvotes: 1
Reputation: 184
To debug can you switch around #box and #cat?
You are using an else, so if #cat is empty, you will not see the message "the box field is empty". It will only show this message if #cat is not empty, and #box is.
change #box to something you know doesn't exist (and cannot exist). perhaps there is a value in it.
you could ouput the value of #cat and #box to the console to ensure that they are empty.
console.log("$.trim($("#cat").val()="+$.trim($("#cat").val()); console.log("$.trim($("#box").val()="+$.trim($("#box").val());
Upvotes: -2
Reputation: 782693
Use separate if
statements for each condition; else if
only runs if the first if
fails. Use a variable to accumulate the messages.
beforeSend: function() {
var msg = '';
if (!$.trim($("#cat").val())) {
$(".fb-error").css( "display", "block" );
msg = "<p>the cat field is empty</p>";
xhr.abort();
}
if (!$.trim($("#box").val())) {
$(".fb-error").css( "display", "block" );
msg += "<p>the box field is empty</p>";
xhr.abort();
}
$(".fb-error").html(msg);
},
Upvotes: 2
Reputation: 9775
You can't use else
if you want to check both conditions.
var error = '';
if (!$.trim($("#cat").val())) {
error = "<p>the cat field is empty</p>";
}
if (!$.trim($("#box").val())) {
error += "<p>the box field is empty</p>";
}
if (error) {
$(".fb-error").html(error);
$(".fb-error").css( "display", "block" );
xhr.abort();
}
In second if
you have to append new html, to prevent overwriting already added message.
Upvotes: 4