0

I have dynamically generated div from the below code in partial view.

$('#album').click(function (e) {
    var l = window.location;
    var base_url = l.protocol + "//" + l.host;
    e.preventDefault();
    $.ajax({
        type: "POST",
        url: base_url + '/CreateAlbum/DisplayAlbum',
        success: function (data) {
            $.each(data, function (index, el) {
                console.log(el);

                for (i = 0; i < el.length; i++) {
                    div = $('<div class="albumclass" />');
                    **img = $('<img  src="/Content/images/fold.jpg" width=150 height=150 assigned-id ='+el[i]["ID"]+'/>').prependTo(div);**

                    lbl = $('<label/>').text(el[i]["title"]).appendTo(div);

                    div.appendTo('.album_inner');

                }

            });
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alert("Error");
        }
    });


});

I need to catch the value of 'assigned-id' of current double clicked image in jquery.I tried the below code but result 'undefined'

 $('.album').on('dblclick', '.albumclass img', function (e) {         

        $("#albumId").val($(this).data('assigned-id'));

    }); 

Anybody please help

Neethu
  • 85
  • 4
  • 9

2 Answers2

0

assigned-id is attribute and not property of element. You need to use .attr('assigned-id'):

 $('.album_inner').on('dblclick', '.albumclass img', function (e) {         
    $("#albumId").val($(this).attr('assigned-id'));
 }); 

Note: you should use .data-* attributes(added in HTML5) for adding custom attributes as adding your own attributes can break elements validation and make html invalid (see https://stackoverflow.com/a/1735239/1719752).

<div class="albumclass">
 <img src="/Content/images/fold.jpg" width="150" height="150" data-assigned-id="9/">
 <label>15Sep2015</label>
</div>

and then use .data() to get set value associated with it:

 $('.album_inner').on('dblclick', '.albumclass img', function (e) {         
    $("#albumId").val($(this).data('assigned-id'));
 }); 
Community
  • 1
  • 1
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

I would recommend you to use data-* prefixed custom attribute

<div class="albumclass">
    <img src="/Content/images/fold.jpg" width="150" height="150" data-assigned-id="9/">
    <label>15Sep2015</label>
</div>

Then you can use data() to fetch it.

 $('.album').on('dblclick', '.albumclass img', function (e) {         
    $("#albumId").val($(this).data('assigned-id'));

    //As per current implementation use
    //$("#albumId").val($(this).attr('assigned-id'));
 }); 
Satpal
  • 132,252
  • 13
  • 159
  • 168