Search code examples
jquerymodal-dialoghref

pass href text to modal


I have a table with usernames and the names of the users are links which when clicked show a modal. In this modal, the user's password can be changed. I want to get the text of the href in the modal. My code is below:

<td>
    <a href='#' data-toggle='modal' data-target='#useredit'>username</a>                
</td>

I want to see the username that was clicked in the modal.

<div id="useredit" 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">User Edit</h4>
            </div>
            <div class="modal-body">
                <form class="forma" role="form" method="POST" action="#">
                    <div class="form-group">
                        <div class="form-group">
                            <label for="newpass">Password</label>
                            </label>
                            <input type="text" name="newpass" class="form-control" placeholder="Password must be 8 charachters long!" id="newpass" maxlength="20" />
                        </div>

                        <div class="form-group">
                            <label for="newpass2" >Retype Password</label>
                            </label>
                            <input type="password" name="newpass2" class="form-control" placeholder="Retype Password" id="newpass2" onkeyup="checkPass(); return false;" maxlength="20"/>
                            <span id="confirmMessage" class="confirmMessage"></span>
                        </div>
                    </div> 
                    <button type="submit" class="btn btn-default" id="btn1" >Submit</button>
                </form>
            </div>      
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
    </div>
</div>
</div>

Solution

  • You can use .on(shown.bs.modal) of bootstrap as below and get its relatedTarget of event and fetch its text as below:

    DEMO

    $('#useredit').on('shown.bs.modal',function(e){
        $(this).find('.modal-title').html($(e.relatedTarget).text());
    });