Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/xamarin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript在提交时遍历所有复选框,如果从原始值更改,则设置属性_Javascript_Checkbox - Fatal编程技术网

Javascript在提交时遍历所有复选框,如果从原始值更改,则设置属性

Javascript在提交时遍历所有复选框,如果从原始值更改,则设置属性,javascript,checkbox,Javascript,Checkbox,我尝试创建一个类似于以下内容的javascript函数,只是当用户单击submit按钮时,它会遍历所有复选框: $('.checkboxstatus').click(function(){ this.setAttribute('checked',this.checked); if (this.checked && $(this).data("def") == 0){ //checkbox has changed this.setA

我尝试创建一个类似于以下内容的javascript函数,只是当用户单击submit按钮时,它会遍历所有复选框:

$('.checkboxstatus').click(function(){
this.setAttribute('checked',this.checked);
if (this.checked && $(this).data("def") == 0){
             //checkbox has changed
            this.setAttribute('changed', 'yes');
    }
    else if(!this.checked && $(this).data("def") == 'checked')
    {
            //checkbox has changed
            this.setAttribute('changed', 'yes');
    }
    else{
        //no change in checkbox
        this.setAttribute('changed', 'no');
        }
 });

当用户单击submit时,应调用该函数,并遍历所有复选框,查看是否选中该复选框,以及是否选中数据定义或0。如果选中该复选框并选中data def=“checked”,则不会发生任何事情。如果复选框状态与数据定义不同,则应向该复选框添加一个值为“是”的属性(“已更改”)。有什么建议吗?

你的问题几乎能给你答案。您需要在表单上附加一个“提交”事件处理程序,然后抓取所有
输入[type=checkbox]
,并相应地设置“changed”属性。

我不确定我是否了解这一点,但通常的做法是在
数据中设置初始状态,然后在提交时阻止提交操作,选中该初始状态
数据
变量的所有复选框,查看是否有任何更改,如果更改,是否触发本机提交处理程序

var boxes = $('input[type="checkbox"]').each(function() {
    $(this).data('initial_state', this.checked);
});

$('form').on('submit', function(e){
    e.preventDefault();

    var same_same = true;

    boxes.each(function() {
        if ( $(this).data('initial_state') !== this.checked ) { // has changed ?
            $(this).data('changed', true);
            same_same = false;
        }
    });

    if ( ! same_same ) { // diffelent
        this.submit();
    } else {
       alert('same same, but not diffelent!');
    }

 });

我认为这是正确的,我们将复选框的选中状态与每个复选框上的数据定义属性进行比较