pmn
pmn

Reputation: 2247

Onclick function fires Twice with one click

I have a foreachin the razor :

<ul>
    @foreach (var node in Model)
    {
        var par = node.Id;
        <li onclick="GetSubMenu(this)" id="@node.Id">
            @node.Title
        </li>
    }
</ul>

in onclick i called method in the :

function GetSubMenu(e) {
    debugger;
    $.ajax({
        type: "Get",
        url: "/Menu/GetSubMenu",
        data: { parentId: e.id },
        contentType: "application/json; charset=utf-8",
        dataType: "json",

    }).done(function (result) {
        $.each(result, function (index, val) {               
            $("#" + val.ParentId).append("<ul><li onclick='GetSubMenu(this)' id='" + val.Id + "'>" + val.Title + "</li></ul>");

        });
    });
}

and in controller i return the submenu of parent menu(which i click on it):

   public JsonResult GetSubMenu(string parentId)
    {
        int id = int.Parse(parentId);
        return Json(db.PrmMenus.Where(x => x.ParentId == id), JsonRequestBehavior.AllowGet);
    }

the first time all thing was ok, and the sub menu will show properly, but in seccond time when i click on submenu, the onclick function call for submenu and the parent menu again, what is the problem?

Upvotes: 0

Views: 3665

Answers (1)

Shyju
Shyju

Reputation: 218732

The problem is, when you click on the child element, It is calling the onclick event for the child element and parent element because child is contained inside the parent!

You can use jQuery stopPropogation method to stop bubbling the event. this method prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.

Converting your code to unobtrusive javascript

<li class="menuItem" id="@node.Id">
     @node.Title
</li>

and listen to the click event on the items with "menuItem" class

$(function(){

   $(document).on("click",".menuItem",function(e){
       e.stopPropagation();

       var id=$(this).attr("id");
       ///Do your ajax call here
   });

});

Make sure you build the same sort of markup for child elements in your ajax method's done event (one with the same css class)

Here is a working jsfiddle

Upvotes: 2

Related Questions