-1

I have a main view that has a button "AddSkillBtn" which on clicked shows a modal popup witha partial view inside. Works fine so far. I have a link inside the partial view "addAnotherSkill" which on clicked has to show an alert. However, the click event doesn't get fired at all. Please find below the code snippet - Any help much appreciated!!

**jQuery:** 

$('#AddSkillBtn').click(function (e) {    
            $.ajax({
                url: '@Url.Action("MyAction", "MyController")',
                type: "POST"
                
                success: function (result) {
                    $("#AddContainer").html(result);

                    $('#AddModal').modal('show');
                }
            });
        });

$("#addAnotherSkill").on('click', function () {
           
            alert("Hi!!");

        });
**Main View**

<p><a id="AddSkillBtn" href="javascript:void(0)" class="btn btn-rounded btn-primary">Add new Skill</a></p>


<div class="modal modal-wide fade" id="AddModal" tabindex="-1" role="dialog" aria-labelledby="AddLabel" aria-hidden="true">
    <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 class="modal-title" id="AddLabel">Add New Skills</h4>
            </div>
            <div class="modal-body">
                <div id="AddContainer">
                </div>
            </div>
        </div>
    </div>
</div>

   
**Partial View rendered in the modal popup has**

        <a id="addAnotherSkill" href="javascript:void(0)"><i class="fa fa-plus"></i> Add Another</a> //clicking on this link does nothing
solar
  • 29
  • 1
  • 8
  • Looks like the element with `id="addAnotherSkill"` is being added dynamically,in which case it needs to be `$(document).on('click', '#addAnotherSkill', function () {` (change document to the closest ancestor which exists when the page is first rendered) –  Jan 28 '15 at 23:39

1 Answers1

0

Your element with id="addAnotherSkill" is being added to DOM dynamically. In order to use event delegation using the .on() function, it needs to be

$(document).on('click', '#addAnotherSkill', function (e) {
  e.preventDefault();
  ...
}

Note you should change document to the closest ancestor of the element which exists when the page is first loaded.

Note also the use of e.preventDefault() which means that you can just use <a id="addAnotherSkill" href="#"> (my preference but I have seen arguments for and against - for example the answers here)

Community
  • 1
  • 1