2
function test() {
    $.getJSON("/Home/GetAp", function (result) {
        $.each(result, function () {
            if (this.is_disabled == "False") {
                var a = $("#MainDiv")
                            .append('<div id="imagewrap"><img id="infobutton" src="/Content/information%20icon.png" /></div>')
                            .val(this.id);
            } else if (this.is_disabled == "True") {
                var a = $("#MainDiv")
                            .append('<div id="imagewrap"><img id="infobutton2" src="/Content/information%20icon.png" /></div>')
                            .val(this.id);
            } else {
                return null;
            }
        })
    })
}

How would I nest and ajax function be able to POST the a.val() so that when a user clicks on any $("#infobutton") they will be able to use the val of that button which would be an id specific to that button

$("#infobutton").click(function () {
    $.ajax({
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        url: "/Home/setID",
        data: JSON.stringify({ id: this.id }),
        success: function (result) {

        }
    });
});
Andreas
  • 21,535
  • 7
  • 47
  • 56

2 Answers2

0

Do not make your logic depend on duplicate ids of DOM elements, use class instead.

Use event delegation to register event handlers for elements that exist at the time of event registration and for elements that will be created later.

.append('<div id="imagewrap"><img class="infobutton" src="/Content/information%20icon.png" /></div>')

$(document).on("click",".infobutton",function () {
  $.ajax({
    ...
  });
});
Igor
  • 15,833
  • 1
  • 27
  • 32
  • Tried this, however when I check the value of the id in the method setID, it shows id as null –  Feb 02 '17 at 16:36
  • "check the value of the id in the method setID" - what does it even mean? – Igor Feb 02 '17 at 16:41
0

No need to nest ajax call. Just ensure click events bind to new elements appended and get the id in click event handler. Similar example (without ajax call)

$(document).ready(function(){    

$(document).on('click', '.info', function(e) { alert("clicked div # " +  $(e.target).text()); });

setTimeout(function(){ $("#d1").append("<div class='info'>Click info 1.</div>"); }, 1000);
setTimeout(function(){ $("#d1").append("<div class='info'>Click info 2.</div>"); }, 2000);
setTimeout(function(){ $("#d1").append("<div class='info'>Click info 3.</div>"); }, 3000);
});

<div id="d1">

</div>

Let me know if you need more details or example with ajax call.

For id you can use

$(document).on('click', '.info', function(e) { alert("clicked div # " +  e.target.id); });
Kaushal
  • 1,251
  • 1
  • 8
  • 8