ElenaDBA February 2016

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>

Answers


Darren Davies February 2016

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");
});


charlietfl February 2016

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');
    });


che-azeh February 2016

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');
    });
});

Post Status

Asked in February 2016
Viewed 3,032 times
Voted 10
Answered 3 times

Search




Leave an answer