test
test

Reputation: 301

Validating a form in Twitter Bootstrap Model

I have a form in a modal with some required fields, but when I hit submit the form just reloads and I don't get any message for validation that I am using for submitting the form jQuery, as below :

<script>
    $('#InfroTextSubmit').click(function(){
        $('#InfroText').submit();
    });
</script>

The Twitter Bootstrap Modal Code is :

<!-- Modal1 -->
<div id="myModal1" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
    <h3 id="myModalLabel">Edit Introduction</h3>
  </div>
  <div class="modal-body">
    <form id="InfroText" method="POST">
      <input type="hidden" name="InfroText" value="1"/>
      <table>
        <tr><td>Title</td><td><input type="text" name="title" style="width:300px" required="require"/></td></tr>
        <tr><td>Introudction</td><td><textarea name="contect" style="width:300px;height:200px"></textarea></td></tr>
      </table>
    </form>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button class="btn btn-primary" id="InfroTextSubmit">Save changes</button>
  </div>
</div>
<script>
    $('#InfroTextSubmit').click(function(){
        $('#InfroText').submit();
    });
</script>

So how can i Validate the Form and not let the model close and reload if something is wrong with the form ?

Regards,

Upvotes: 3

Views: 22953

Answers (2)

Carol Skelly
Carol Skelly

Reputation: 362390

You can add "data-dismiss=modal" to the InfroTextSubmit button, and then use 'return false' on the '#InfroTextSubmit' click function to prevent the form from closing. If the form is valid you call 'submit()'.

Button code:

<button class="btn btn-primary" data-dismiss="modal" aria-hidden="true" id="save">Save changes</button>

Click function:

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

    if ($('#myField1').val()==="") {
      // invalid
      $('#myField1').next('.help-inline').show();
      return false;
    }
    else {
      // submit the form here
      $('#InfroText').submit();
      return true;
    }     
});

There a several different approaches to the validation itself.

Working on Bootply: http://bootply.com/60244

Upvotes: 3

iCode
iCode

Reputation: 9202

You don't have to add any script for validating form text fields if you added the required attribute.

Try this

<input type="text" name="title" style="width:300px" required="required"/>

or

<input type="text" name="title" style="width:300px" required/>

Upvotes: 8

Related Questions