Display an alert with javascript if checkbox value is different from original checked/unchecked state

StackOverflow https://stackoverflow.com/questions/22156404

  •  19-10-2022
  •  | 
  •  

So basically I have several checkboxes that are checked or unchecked, depending on values in a mysql database. Their checked/unchecked values are also stored in an attr called "def" which is either 0, or checked. I also have some javascript I have written that applies an attr to the checkboxes called "checked", which changes when you check and uncheck boxes. So what I want to do is compare these two values in javascript, when the checked attr is changed when the user clicks on a checkbox, if the checked attr is true and def is 0, then it should send out an alert saying the value is different from the default value, otherwise it should do nothing if def is 0, and checked is false. I am learning javascript and this is what I have so far in JSfiddle: http://jsfiddle.net/FCrSg/89/

Here is my HTML checkbox:

<input class='checkboxstatus' def='0' type=checkbox></input>

and my javascript:

$(document).ready(function(){
$('.checkboxstatus').click(function(){
    this.setAttribute('checked',this.checked);
    if($(this).checked && $(this).def == '0'){
    //checkbox has changed
    alert('checkbox has changed from original value');
    }
 });
 });
有帮助吗?

解决方案

The proper syntax would be

if (this.checked && $(this).attr("def") == 0)

However, def isn't a recognized or valid attribute, it should be data-def to be completely valid. Then you can do:

if (this.checked && $(this).data("def") == 0)

其他提示

Here is a working Fiddle: http://jsfiddle.net/cEGks/1/.

You need to use the jQuery function .attr() (documentation) to get the def attribute. I also changed it to data-def for better browser support and broke the logic into another function for readability.

You also do not need to set an attribute checked on the checkbox. You can just use jQuery's .is(':checked') to check if it is checked.

Here is the code:

HTML:

<input class='checkboxstatus' data-def='1' type="checkbox" />

JS:

$('.checkboxstatus').click(function(){
    if(checkboxChangedFromOriginal($(this))) {
        alert('checkbox has changed from original value');
    }
 });

function checkboxChangedFromOriginal(checkbox) {
 return (checkbox.is(':checked') && checkbox.attr('data-def') == '0') ||
     (!checkbox.is(':checked') && checkbox.attr('data-def') == '1');  
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top