0

我正在开发 CMS。当用户想要替换现有的缩略图图像时,他们可以上传替换图像,并选中复选框以证明他们确实正在替换图像。该复选框似乎是必要的,因为否则表单会提交一个空白值(由于上传字段的空白默认值,所有浏览器的安全默认值)并在没有指定替换图像的情况下清除现有图像。

问题是我一直忘记手动激活复选框并且上传的图像实际上并没有替换现有的图像,因为如果没有选中复选框,接收的 PHP 文件不会(按设计)处理上传的文件名。我怀疑用户会遇到同样的问题,我想通过减少所需步骤的数量来防止这种情况发生。一种解决方案是在单击上传字段时使用 jQuery 检查复选框。那么为什么这不起作用:

$('#image_req').click(function () {
    if ($('#checkbox_req').attr('checked',true)) {
        $('#checkbox_req').removeAttr('checked');
        alert('Unchecked');
    } else if ($('#checkbox_req').attr('checked',false)) {
        $('#checkbox_req').attr('checked','checked');
        alert('Checked');
    }
});

有问题的 HTML 如下所示:

<input id="image_req" name="local_filename" type="file" />
<input id="checkbox_req" name="replace_image" value="yes" type="checkbox" />
4

5 回答 5

0

I ended up using a hidden input, which was the obvious solution, and one that I've implemented before, but somehow overlooked this time. But I appreciate all the varied and helpful responses. Stack Overflow rocks.

于 2010-05-17T14:56:19.790 回答
0

@Arne

我尝试快速运行您的代码,但由于某种原因,它每次都取消选中它。我很快对其进行了修改,以便每次都选中复选框。据我所知,没有必要取消选中该框,对吗?

$('#image_req').mouseup(function () {
    if ($('#checkbox_req').attr('checked',false)) {
        $("input[name='replace_image']").attr('checked', true);
    }
});

@Doug:感谢您的提示

于 2010-05-15T21:11:47.173 回答
0

您的 if 条件无法正常工作,因为您实际上是assigning价值而不是获得它们。尝试这个:

$('#image_req').click(function () {
    var checkbox = $('#checkbox_req');
    if (checkbox.is(':checked')) {
        checkbox.removeAttr('checked');
        alert('Unchecked');
    } else {
        checkbox.attr('checked', 'checked');
        alert('Checked');
    }
});

但这有意义吗?当用户首先手动选中该框然后点击上传时,它会再次取消选中。

默认情况下,我会通过checked在 HTML 中设置属性来检查它。如果用户不想替换图像,他可以手动取消选中它。

PS:如果您确实需要始终选中此复选框,那么简单地将复选框变成隐藏字段怎么样?

<input id="checkbox_req" name="replace_image" value="yes" type="hidden" />

如果由于任何原因无法做到这一点,这里有另一个具有相同效果的想法:使用 javascript 选中该框并通过 CSS 将其隐藏。

于 2010-05-15T21:17:40.847 回答
0

可能是 $ 与您的 CMS 中现有的 javascript 库冲突。我不得不对选择框做类似的事情,并发现了 jQuery.noConflict:

jQuery.noConflict();

jQuery(document).ready(function() {
    //preselect sectionid
    jQuery('select[name="sectionid"] option[value="29"]').attr("selected", true);
    jQuery('select[name="sectionid"] option[value="29"]').trigger("change");
    jQuery('select[name="access"] option[value="1"]').attr("selected", true);
});

在“jQuery.noConflict();”之后 你可以使用“jQuery”而不是“$”

同样在我的情况下,我必须触发更改事件,因为“访问”选择框的内容取决于“sectionid”选择框中选择的内容

于 2010-05-15T15:52:57.497 回答
0

您不能在隐藏输入 ( type="hidden") 中包含默认值吗?这样,当您提交表单时,您就知道默认值是什么。如果没有任何变化,使用默认值或什么都不做,如果文件被上传(检查$_FILES),使用新文件。

于 2010-05-15T15:55:44.660 回答