Dhanu Gurung
Dhanu Gurung

Reputation: 8840

Validate bootstrap modal fields on click of button

I am using twitter bootstrap modal to get 'Start' and 'End' date for some course.

<div id="save_course_modal" class="modal hide fade">
  <div class="modal_header_class">
    <h4>Start Course</h4>
  </div>
  <div class="modal-body">
    <label class='selector_modal_label'>Course</label>
    <table class="table">
      <thead>
        <tr>
          <th>
            <p>Start date: <input type="text" id="start_date" size="30" /></p>
          </th>
          <th>
            <p>End date: <input type="text" id="end_date" size="30" /></p>
          </th>
        </tr>
      </thead>
    </table>
  </div>
  <div class="modal-footer modal_footer_class">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
    <button id='add_course' class="btn btn-primary" data-dismiss="modal" aria-hidden="true">Start</button>
  </div>
</div>

My Use Case:

I want to validate two input fields with ids 'start_date' and 'end_date'. Since, it is not a form and hence couldn't use 'required' attribute.

I am thinking to use following:

  1. Remove data-dismiss="modal" aria-hidden="true" from button with id='add_course'.
  2. Add onclick='validate_course_fields();' to above button.
  3. If validations are fine then hide modal through $('#save_course_modal').hide();

Any better solution is appreciated.

Upvotes: 0

Views: 3429

Answers (1)

First it would be best to avoid using tables to align the elements in modal.

<div id="save_course_modal" class="modal hide fade">
    <div class="modal_header_class">
        <h4>Start Course</h4>
    </div>
    <div class="modal-body">
        <label class='selector_modal_label'>Course</label>
        <div class="form-group">
            <label class="control-label col-sm-2"> Start Date:</label>
            <div class="col-sm-10>
                <input type="text" id="start_date" class="form-control" size="30" /> 
            </div>
        </div>
        <div class="form-group">
            <label class="control-label col-sm-2"> End Date:</label>
            <div class="col-sm-10>
                <input type="text" id="end_date" class="form-control" size="30" />
            </div> 
        </div>  
    </div>
    <div class="modal-footer modal_footer_class">
        <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
        <button id='add_course' class="btn btn-primary">Start</button>
    </div> 
</div>

In your javascript code you should use the event hide of the Bootstrap that can be seen in http://getbootstrap.com/javascript/#modals

$("#add_course").click(function(e){
    e.preventDefault(); //remove the default button action

    //validation
    if(validate_form()){
        //When validation is OK

        //hide modal using event of the Bootstrap
        $("#save_course_modal").modal("hide");
    }
})

Upvotes: 0

Related Questions