Checkbox: Zustandswechsel verhindern mit jQuery

by Oliver 11. November 2010 16:15

Untertitel (wonach ich bei Google suchen würde, um diese Lösung zu finden): How to prevent unchecking of a checked checkbox (using jQuery, for example).

Wie verhindert man das Abwählen einer ausgewählten Checkbox? Mit jQuery wie folgt:

   1: <script type="text/javascript">
   2:     
   3:     $(function () {
   4:  
   5:         // Prevent from unchecking checked checkboxes
   6:         $('table.image-change input:checkbox').mousedown(function (ev) {
   7:             
   8:             // remove the nasty ASP.NET onclick event handler in case the checkbox is already checked
   9:             $(this).filter(':checked').removeAttr('onclick');
  10:  
  11:         }).click(function (ev) {
  12:  
  13:             // when we get here the checkbox state has already changed!
  14:             if ($(this).is(':not(:checked)')) {
  15:                 // but we prevent the change from "materializing"!
  16:                 ev.preventDefault();
  17:                 ev.stopPropagation();
  18:             }
  19:  
  20:         });
  21:     });
  22:  
  23: </script>

Zu beachten ist hier, dass der mousedown-Eventhandler nur dafür da ist, aus einer schon angewählten Checkbox den statischen onclick-Handler zu entfernen, da dieser ansonsten aller Bemühungen im click-Handler (darunter) zum Trotz weiterhin feuert.

Hat mich einiges an Schweiß gekostet, aber jetzt funktioniert’s :-)

Happy Coding,

Oliver

enjoyed the post?

Tags:

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

About Oliver

shades-of-orange.com code blog logo I build web applications using ASP.NET and have a passion for javascript. Enjoy MVC 4 and Orchard CMS, and I do TDD whenever I can. I like clean code. Love to spend time with my wife and our children. My profile on Stack Exchange, a network of free, community-driven Q&A sites

About Anton

shades-of-orange.com code blog logo I'm a software developer at teamaton. I code in C# and work with MVC, Orchard, SpecFlow, Coypu and NHibernate. I enjoy beach volleyball, board games and Coke.