-2

I am using jQuery to replace normal checkbox with image. I am able to replace checkbox with image but unable to set CSS and click handler on image.

This is my jQuery code.

(function ($) {
    $.fn.SetOnOff = function (onImage,offImage) {
         debugger;
         var html = '<img style="width: 80px; height: 30px" src="'+offImage +'"/>';
                $(this).replaceWith(html);
         $(html).css('cursor','pointer');
          $(html).click(function(){
             var fileName = $(this).attr('src');
                if (fileName == onImage)
                    $(this).attr('src', offImage);
                else
                    $(this).attr('src', onImage);
         });
                
        return  $(this);
    };
} (jQuery));

can anybody let me know how to do this?

you use This link to test it

Manish
  • 101
  • 2
  • 18

3 Answers3

3

use event delegation for dynamically created element

$("button").click(function () {
    var v = "<div>" + $(this).text() + "</div>";
    $(this).replaceWith(v);
    $(v).css('cursor', 'pointer');
});

$(document).on("click", "div", function () {
    alert($(this).text());
});

DEMO

Balachandran
  • 9,427
  • 1
  • 14
  • 25
2

you are trying to set css to string. make it jquery object just like below

(function ($) {
$.fn.SetOnOff = function (onImage,offImage) {
     debugger;
     var html = $('<img style="width: 80px; height: 30px" src="'+offImage +'"/>');
            $(this).replaceWith(html);
     $(html).css('cursor','pointer');
      $(html).click(function(){
         var fileName = $(this).attr('src');
            if (fileName == onImage)
                $(this).attr('src', offImage);
            else
                $(this).attr('src', onImage);
     });

    return  $(this);
};
} (jQuery));

Demo

Mohit Kumar
  • 9,065
  • 2
  • 27
  • 43
2

Your css and click methods are not being called on the replaced element but on a newly-created HTML jQuery is generating from your html string.

Try this instead:

 var $v = $("<div>" + $(this).text() + "</div>");
 $(this).replaceWith($v);
 $v.css('cursor', 'pointer');
 $v.click(function () {
     alert('a');
 });
haim770
  • 47,051
  • 7
  • 96
  • 126