-1

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
  • 103
  • 3
  • 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,567
  • 1
  • 16
  • 26
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
  • 48,394
  • 7
  • 105
  • 133
1

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

Umesh Sehta
  • 10,555
  • 5
  • 39
  • 68