AomSet
AomSet

Reputation: 383

Adding checkbox with JS, and find it in server side code (ASP.NET)

I am making a page where all the images are retriaved from the server/database, and shown on the page. For this I use AJAX. The code below retrieves an array with references to images, and an index. From that info I line up the images. What I want to do, is to give the user the possibility to delete chosen images. These images should be chosen through a checkbox. My problem is that I don't know how to add a checkbox (below the image) so that it corresponds to each image, and also find that checked value in the C# code. I will need to find it, since I have to find the checked image in the database and delete it. Does anyone know how to do this? Normally to find an ID in the C# code, we apply the runat="server" on the aspx page, but this time, the IDs are added dynamically, and with JS code.

function loadImage(array, index) { 
    for (i = 0; i < array.length; i++) {
        $("#parentDiv").append("<span style='padding-left: 10px; margin-top: 5px;' id='span_" + i + "'></span>");
        $("#span_" + i + "").append("<img style='width: 100px; height: 90px;' id='img_"+i+"' src='" + array[index] + "' />");
        index++;
    }
}

Upvotes: 0

Views: 550

Answers (1)

Mister Epic
Mister Epic

Reputation: 16733

In cases like these, I like to take advantage of HTML5 data attribute (http://www.w3.org/TR/2010/WD-html5-20101019/elements.html#embedding-custom-non-visible-data-with-the-data-attributes) This allows you to embed a target for your checkbox in its markup. The following hasn't been tested, and I took a guess about your checkbox markup, hopefully it gives you the idea.

function loadImage(array, index) { 
    for (i = 0; i < array.length; i++) {
        var imageId = 'img_"+i+"';
        $("#parentDiv").append("<span style='padding-left: 10px; margin-top: 5px;' id='span_" + i + "'></span>");
        $("#span_" + i + "").append("<img style='width: 100px; height: 90px;' id='" + imgeId + "' src='" + array[index] + "' />");
        $("#parentDiv").append('<input type="checkbox" class="imgDelete" name="imgCheck" data-image-target="' + imageId + '">')
        index++;
    }
}

Then you bind a handler to your checkboxes like so:

$('imgDelete').click(function(e){
    var idOfImageToDelete = $(this).attr('data-image-target');
    ///Call to web service to delete image
});

You can also embed data with jQuery's data() function, but I personally prefer seeing the data written into the element's markup so I can better review it with my developer toolkit.

Upvotes: 1

Related Questions