简体   繁体   中英

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 image 在此处输入图片说明

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);
        }
    });
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM