thecreator thecreator - 19 days ago 11
Javascript Question

Prevent ajax submit with blank inputs and selects

I'm stuck on here:

//Saving Data
$('#saveButton').click(function(){

var teamA = $('#teamA').val();
var teamB = $('#teamB').val();
var date = $('#date').val();
var timeOfEvent = $('#timeOfEvent').val();
var live = "0";
if($("#live").is(':checked'))
live = $('#live').val();

$.ajax({
url : "ajax.php",
type : "POST",
async: false,
dataType: "json",
data :
{
'submitAddEvents' : 1,
'teamA' : teamA,
'teamB' : teamB,
'date' : date,
'timeOfEvent' : timeOfEvent,
'live' : live,
},
success:function(data)
{

if(!data.success) {
alert(data.message);
}else{
window.location = "addEvents.php";
}

}
});
});


That's what I already have.. It's "everything" ok BUT even with
required
in
inputs
and
selects
when I click on button It inserts the data into the database without prevent the blank inputs or selects...

WHAT I ALREADY DID
I put a
<form>
and I changed my ajax

$('#saveButton').click(function(){


to

$('#saveButton').submit(function(ev){
ev.preventDefault();


And didn't work.. In this case It blocks the empty inputs but when I fill the inputs and click on button nothing happens..

Answer

you must select your form, not your button to attach submit listener, instead of this:

$('#saveButton').submit(function(ev){
ev.preventDefault();

change to:

$('#myform').submit(function(ev){
ev.preventDefault();
Comments