Asesha George Asesha George - 1 month ago 8
HTML Question

how to hide Bootstrap modal window if from field is not valid

i am trying to send form data and get response using jquery and display it in a modal window. every form field is required so i am using attb required. on click submit data should submit to jquery and fetch response. but if any of the field is empty error should display. now the problem is its also toggle the modal window. please see my code below.

<form name="newjoin" method="post" enctype="multipart/form-data" id="JoiningConform">

<label for="sponsorid">Name: <span class="req">*</span></label>
<input type="text" id="name" name="name" placeholder="Your Name" class="form-control" tabindex="1" required />

<button type="submit" data-toggle="modal" href="#myModal" class="button btn btn-primary btn-large">Register</button>


<div id="myModal" class="modal fade in">
<div class="modal-dialog">
<div class="modal-content">

<div class="modal-header">
<a class="btn btn-default pull-right" data-dismiss="modal"><span class="fa fa-remove"></span></a>
<h4 class="modal-title">CONGRALUATIONS</h4>
</div>
<div class="modal-body">
<h4>Text in a modal</h4>
<p>Duis mollis, est non commodo luctus, nisi erat porttitor ligula.</p>
<div id="modal-div"></div>
</div>

</div><!-- /.modal-content -->
</div><!-- /.modal-dalog -->
</div><!-- /.modal -->


my jquery is

$('form#JoiningConform').on('submit',function(event){
event.preventDefault()

$.ajax({
type:'post',
url:'testmodal.php',
data:$('form#JoiningConform').serialize(),
success: function(response){
if(!response){
$('#modal-div').html(response).modal('show');
}
}
});
});


my concern in if i click on button if any field is empty it should show only error after success response only modal Window should appear.

example imageenter image description here

zed zed
Answer

Try this... First validate the name field.

$('form#JoiningConform').on('submit',function(event){
  event.preventDefault()
  var name = $('#name').val();
  if(name == ""){
    alert('error message');
    return false;
  }else{
    $.ajax({
        type:'post',
        url:'testmodal.php',
        data:$('form#JoiningConform').serialize(),
        success: function(response){
            $('#myModal').modal('show');
            $('#modal-div').html(response);
        }
    });
  }
});
Comments