Search code examples
javascriptjquery

How to scroll to the top of a modal window in javascript


My requirement is that I need to show a modal window as a form to be filled by user. But the height of that modal should be not more then window size.

So if the entries in form are too much then the modal becomes scrollable. The problem is that while validating the entries in the form the error message is shown at the top of the modal above the first entry. If user is at last property then he will not be knowing that some validation error had occurred unless the modal is scrolled to top on the error event.

I have tried :

$(window).scrollTop();
// and
$('#modalId').scrollTop();

this is the modal code:

<div class="modal hide" id="groupModal" tabindex="-1" role="dialog" aria-hidden="true" >
    <div class="modal-header">
    </div>
    <div class="modal-body" style="max-height: 300px;">
        <div class="grpForm">
            <div class="alert alert-error hide">

                <span class="errMsg"></span>
            </div>
            <div class="alert alert-success hide">

                <span class="successMsg"></span>
            </div>
            <form class = "formFieldHolder" id="groupInfoForm"></form>
          </div>
    </div>
    <div class="modal-footer">
        <button class="btn cancelFormBtn" data-dismiss="modal" aria-hidden="true" msgkey="common.cancel.label"></button>
        <button class="btn btn-primary submitGroupFormBtn" type="submit" msgkey="common.submit.label"></button>     
    </div>
</div>

Solution

  • $('#modalId').scrollTop(0);

    scrollTop() only returns the value; scrollTop(0) sets the value to 0 (all the way to the top)