jQuery>在复选框更改运行代码

时间:2012-09-26 03:43:34

标签: javascript jquery

我在核对清单上有“待办事项”行,每行都有一个“已完成”复选框。使用鼠标单击该框后,以下代码将运行并正确发布信息(更新数据库以跟踪任务已完成):

   $(function ()
 {
     $('[id*="howto_step_complete"]').mousedown(function ()
     {
         var id = $(this).attr('id');
         var howto_used_id = id.substr(id.length - 2);

         var howto_step_minutes = $('#howto_step_minutes' + howto_used_id).val();

         if (!$(this).is(':checked'))
         {
             var checked = true;
         }
         else
         {
             var checked = false;
         }
         var value = $('#howto_used_id').val();
         if (howto_step_minutes != '')
         {
             $.post("updateChecklist.php",
             {
                 howto_used_id: howto_used_id,
                 howto_step_complete: checked,
                 howto_step_minutes: howto_step_minutes
             },

             function (data)
             {
                 var obj = jQuery.parseJSON(data);
                 var howto_used_id_returned = obj.howto_used_id;
                 var howto_step_complete = obj.howto_step_complete;
                 alert(howto_step_complete);
             });
             $(this).trigger("change");
         }
         else
         {
             alert('Minutes must be filled out before checking complete');
         }
     });

 });

问题是,如果一个人使用制表符在表单中移动然后使用空格键来检查框,则不会触发,因为它使用的是mousedown。我尝试将其更改为change(),但之后我的警报框一直反复出现“false”。

应该是真的,因为我刚刚检查了这个盒子,我不明白为什么它会不断出现。

我可以使用什么代替mousedown()来使此代码正确发布?

2 个答案:

答案 0 :(得分:1)

我将其更改为再次使用change()然后删除触发器,我认为这是不断弹出警告框然后再次更改它并循环播放。

$(function(){
        $('[id*="howto_step_complete"]').change(function() {
        var id = $(this).attr('id');
        var howto_used_id = id.substr(id.length - 2);

        var howto_step_minutes = $('#howto_step_minutes' + howto_used_id).val();

        if (!$(this).is(':checked')) { var checked = false; }else{ var checked = true; }
            var value = $('#howto_used_id').val();
            if(howto_step_minutes!=''){
             $.post("updateChecklist.php", { howto_used_id: howto_used_id, howto_step_complete: checked, howto_step_minutes: howto_step_minutes },
                        function(data) {
                        var obj = jQuery.parseJSON(data);
                           var howto_used_id_returned = obj.howto_used_id;
                        var howto_step_complete = obj.howto_step_complete;
                        alert(howto_step_complete);
                   });
            }else{ alert('Minutes must be filled out before checking complete'); }
        });

});

我还检查了错误/反转的真/假。修正了这一点。

答案 1 :(得分:0)

相关问题