Search code examples
javascriptjquerybootstrap-modal

e.preventDefault is not working while openning A modal after changing modal-text. modal is openning without changing content


I am trying to change the modal-body text when modal trigger button is clicked . The modal is opening but the modal-body text is not changing. This is the code for modal:

<button type="button" class="btn btn-info open-modal" data-remote="false" data-toggle="modal"  data-target="#myModal">Register</button>

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">

        <!-- Modal content-->
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal">&times;</button>
                <h4 class="modal-title">Modal Header</h4>
            </div>
            <div class="modal-body">
                <p>Some text in the modal.</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
            </div>
        </div>

    </div>
</div>

Then source for preventing default event

$('.open-modal').click(function(e)
{
    e.preventDefault();
    alert('hello i am jquery');
    $('#myModal').modal('show');
});

Why alert('hello i am jquery'); line is not executing ?


Solution

  • This may happen when your HTML takes precedence over jquery since your button specifes the target modal to open with the following attributes

    data-remote="false" data-toggle="modal"  data-target="#myModal"
    

    Remove those and then the jquery will be fine

    $('.open-modal').click(function(e)
    {
        e.preventDefault();
        alert('hello i am jquery');
        $('#myModal').modal('show');
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
    
    <button type="button" class="btn btn-info open-modal" >Register</button>
    
    <!-- Modal -->
    <div id="myModal" class="modal fade" role="dialog">
        <div class="modal-dialog">
    
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">&times;</button>
                    <h4 class="modal-title">Modal Header</h4>
                </div>
                <div class="modal-body">
                    <p>Some text in the modal.</p>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                </div>
            </div>
    
        </div>
    </div>