Reputation: 383
I am trying to be able to get my form to check if the 2 input boxes have any data input into them before it submits. The reason I am having trouble with this is because I am using the following -
$('form.ajax').on('submit', function () {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function (index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
})
this.reset();
return false;
});
This makes it so the form is submitted without the page having to refresh, I also have an image appear for a few seconds when the submit button has been pressed -
$(".bplGame1Fade").click(function(){
$("#bplGame1ThumbUp").fadeIn(1000);
$("#bplGame1ThumbUp").fadeOut(1000); });
I don't want these to run unless both the input boxes have data in them. I have tried using OnClick() and OnSubmit(). When using these the message appears saying it isn't a valid entry as I want but once you click OK the form continues to submit.
Is there anyway I can run a JS function to check the input boxes and if one of the boxes is empty, cancel the submission.
Any help with this would be appreciated,
Thanks.
Upvotes: 0
Views: 224
Reputation: 984
Why dont you just add an if condition to check if you ever get an empty input? You can return the function if it's not valid.
$('form.ajax').on('submit', function () {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
var context = this;
var valid = true;
var total = that.find('[name]').length;
that.find('[name]').each(function (index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
if (!value) {
valid = false;
return;
}
data[name] = value;
if (index === total - 1) { //last item
if (valid) {
$.ajax({
url: url,
type: method,
data: data,
});
context.reset();
}
}
});
});
EDIT: You could put the ajax call inside of the foreach. So on the last item, you would make the ajax call if every input had a value.
Upvotes: 1