sincos sincos - 2 years ago 68
jQuery Question

Fill content in modal, when click on <a> tag the click event is not fired

I try to open a modal. When the user clicks on the "Read More", the modal is launched but I need to set up the content dynamically using jQuery. In the debugger, it looks like the click is not fired, the fields aren't set up...


<a id="questionModal-13" href="#modalFAQ" data-toggle="modal" data-questiontitle="Why this?" data-questionanswer="test answer 1"> Read more</a>

<a id="questionModal-24" href="#modalFAQ" data-toggle="modal" data-questiontitle="Why that?" data-questionanswer="test answer 2"> Read more</a>


<div class="modal fade" id="modalFAQ">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
<h4 id="questionTitle" class="modal-title">Modal title</h4>
<div class="modal-body">
<p id="questionAnswer" >Here settings can be configured...</p>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal"><?php echo _('Close') ?></button>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->


var question = $(this).data('questiontitle');
var answer = $(this).data('questionanswer');

$("#questionTitle").html( question );
$("#questionAnswer").html( parseJSON( answer ) );

The modal is correctly launching nor the field in the modal. When I place a breakpoint in the jQuery on click, it's not firing...

I've also tried that form :

jQuery('[id^=questionModal-]').click(function(){ ... });

jquery and bootstrap libraries are loaded...

Some one can help me please?

Answer Source

Since Bootstrap modal fires many events it can be handy to use one of them instead of binding other events on the target click.

If your modal works, than you can be sure this events are fired.

As the documentation sates:

This event fires immediately when the show instance method is called. If caused by a click, the clicked element is available as the relatedTarget property of the event.

You can use event in this case like that:

$('#modalFAQ').on('', function (e) {
    var question = $(e.relatedTarget).data('questiontitle'),
        answer = $(e.relatedTarget).data('questionanswer');
    $("#questionTitle").html( question );
    $("#questionAnswer").html( answer );
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download