Coding Duchess
Coding Duchess

Reputation: 6919

Passing element attribute to JQuery event

I have an html page with several hyperlinks on it that share the same id but have a custom property linkID that differs. I know it is not a good practice but that is not something I can change at this point. I need to open a modal dialog box whenever a link is clicked. For that I am using JQuery. Now I need to pass the linkID property to the Jquery function. I tried using $("#hlk1").attr("LinkID") and $(this).attr("LinkID") but neither worked. It comes up as "undefined".

<html>
<head>
<script src="Script\jquery-2.2.0.js"></script>
<script src="Script\jquery-ui-1.8.24.js"></script>
<script>
$( document ).ready(function() {
    $("#hlk1").click(function(){ 
        var linkId=$("#hlk1").attr("LinkID");
        // initialize dialog
        var dlg = $("#dialog").dialog({ 
            autoOpen: false, height: 500, width: 350
        });

        // load content and open dialog
        dlg.load('page2.html?id=' + linkId).dialog('open');
    });
});

 </script>

</head>
<body>
<a href="#" id="hlk1" linkID="305">Click here</a>
<a href="#" id="hlk1" linkID="890">Click here</a>
<div id="dialog">

</div>
</body>
</html>

Upvotes: 1

Views: 89

Answers (3)

Cedric Ipkiss
Cedric Ipkiss

Reputation: 6347

You need the .data() method. Also use data-attributes properly (data-linkId = "305")

$( document ).ready(function() {
    $("#hlk1").click(function(){ 
        var linkId=$(this).data("LinkID");
        // initialize dialog
        var dlg = $("#dialog").dialog({ 
            autoOpen: false, height: 500, width: 350
        });

        // load content and open dialog
        dlg.load('page2.html?id=' + linkId).dialog('open');
    });
});

Upvotes: 0

Darren
Darren

Reputation: 70766

You need to use linkID not LinkID:

var linkId= $("#hlk1").attr("linkID");

You should also take advantage of using the data attributes.

As an additional note you may have issues with selecting multiple elements with the same identifier with jQuery, therefore it may be better to use a class and attach a handler.

HTML:

<a href="#" class="hlk1" linkID="305">Click here</a>
<a href="#" class="hlk1" linkID="890">Click here</a>

jQuery:

$(".hlk1").on("click", function() {
   var linkId = $(this).attr("linkID");
});

Upvotes: 3

charlietfl
charlietfl

Reputation: 171690

You can't repeat ID's in a page so use class instead. Then inside the click handler this is the element that event occurred on

<a href="#" class="hlk1" linkID="305">Click here</a>
<a href="#" class="hlk1" linkID="890">Click here</a>

JS

 $(".hlk1").click(function(){ 
        var linkId=$(this).attr("linkID");
        // initialize dialog
        var dlg = $("#dialog").dialog({ 
            autoOpen: false, height: 500, width: 350
        });

        // load content and open dialog
        dlg.load('page2.html?id=' + linkId).dialog('open');
    });

Upvotes: 2

Related Questions