如何发布/提交禁用的输入复选框?

发布于 2024-10-13 06:37:22 字数 88 浏览 1 评论 0原文

我有一个复选框,在特定条件下需要禁用该复选框。结果 HTTP 不会发布禁用的输入。

我该如何解决这个问题?即使输入被禁用也提交输入并保持输入禁用?

I have a checkbox that, given certain conditions, needs to be disabled. Turns out HTTP doesn't post disabled inputs.

How can I get around that? submitting the input even if it's disabled and keeping the input disabled?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(18

月下凄凉 2024-10-20 06:37:22

更新READONLY不适用于复选框

您可以使用disabled="disabled",但此时复选框的值不会出现在POST 值。其中一种策略是在同一表单中添加一个隐藏字段来保存复选框的值,并从该字段读取值

只需将disabled更改为readonly

UPDATE: READONLY doesn't work on checkboxes

You could use disabled="disabled" but at this point checkbox's value will not appear into POST values. One of the strategy is to add an hidden field holding checkbox's value within the same form and read value back from that field

Simply change disabled to readonly

っ〆星空下的拥抱 2024-10-20 06:37:22

我已经解决了这个问题。

由于 readonly="readonly" 标签不起作用(我尝试过不同的浏览器),因此您必须使用 disabled="disabled"
反而。但是您的复选框的值将不会发布...

这是我的解决方案:

要同时获得“readonly”外观和POST复选框的值,只需添加与您的复选框具有相同名称和值的隐藏“输入”。您必须将其放在复选框旁边或相同的

标记之间:

<input type="checkbox" checked="checked" disabled="disabled" name="Tests" value="4">SOME TEXT</input>

<input type="hidden" id="Tests" name="Tests" value="4" />

此外,只是为了让您知道 readonly="readonly", readonly ="true"、readonly=""、 或只是 READONLY 无法解决此问题!我花了几个小时才弄清楚!

该参考文献也不相关(可能还没有,或者不再相关,我不知道):
http://www.w3schools.com/tags/att_input_readonly.asp

I've solved that problem.

Since readonly="readonly" tag is not working (I've tried different browsers), you have to use disabled="disabled"
instead. But your checkbox's value will not post then...

Here is my solution:

To get "readonly" look and POST checkbox's value in the same time, just add a hidden "input" with the same name and value as your checkbox. You have to keep it next to your checkbox or between the same <form></form> tags:

<input type="checkbox" checked="checked" disabled="disabled" name="Tests" value="4">SOME TEXT</input>

<input type="hidden" id="Tests" name="Tests" value="4" />

Also, just to let ya'll know readonly="readonly", readonly="true", readonly="", or just READONLY will NOT solve this! I've spent few hours to figure it out!

This reference is also NOT relevant (may be not yet, or not anymore, I have no idea):
http://www.w3schools.com/tags/att_input_readonly.asp

装迷糊 2024-10-20 06:37:22

如果您喜欢使用 JQuery,请在提交表单时删除禁用属性:

$("form").submit(function() {
    $("input").removeAttr("disabled");
});

If you're happy using JQuery then remove the disabled attribute when submitting the form:

$("form").submit(function() {
    $("input").removeAttr("disabled");
});
断桥再见 2024-10-20 06:37:22

创建一个 css 类,例如:

.disable{
        pointer-events: none;
        opacity: 0.5;
}

应用该类而不是禁用属性

create a css class eg:

.disable{
        pointer-events: none;
        opacity: 0.5;
}

apply this class instead of disabled attribute

不必在意 2024-10-20 06:37:22

您可以这样处理...对于每个复选框,创建一个具有相同 name 属性的隐藏字段。但是,请使用一些您可以测试的默认值来设置该隐藏字段的值。例如..

<input type="checkbox" name="myCheckbox" value="agree" />
<input type="hidden" name="myCheckbox" value="false" />

如果提交表单时复选框被“选中”,则该表单参数的值将为

"agree,false"

如果未选中复选框,则该值将为

"false"

您可以使用任何值而不是“false”,但是你明白了。

You could handle it this way... For each checkbox, create a hidden field with the same name attribute. But set the value of that hidden field with some default value that you could test against. For example..

<input type="checkbox" name="myCheckbox" value="agree" />
<input type="hidden" name="myCheckbox" value="false" />

If the checkbox is "checked" when the form is submitted, then the value of that form parameter will be

"agree,false"

If the checkbox is not checked, then the value would be

"false"

You could use any value instead of "false", but you get the idea.

再可℃爱ぅ一点好了 2024-10-20 06:37:22

最简单的方法是:

<input type="checkbox" class="special" onclick="event.preventDefault();" checked />

这将阻止用户取消选择此复选框,并且在提交表单时仍会提交其值。如果您希望用户无法选择此复选框,请删除选中的复选框。

另外,一旦满足特定条件(如果这就是您所追求的),您可以使用 javascript 清除 onclick。这是一个简陋的小提琴,展示了我的意思。它并不完美,但你已经明白了要点。

http://jsfiddle.net/vwUUc/

The simplest way to this is:

<input type="checkbox" class="special" onclick="event.preventDefault();" checked />

This will prevent the user from being able to deselect this checkbox and it will still submit its value when the form is submitted. Remove checked if you want the user to not be able to select this checkbox.

Also, you can then use javascript to clear the onclick once a certain condition has been met (if that's what you're after). Here's a down-and-dirty fiddle showing what I mean. It's not perfect, but you get the gist.

http://jsfiddle.net/vwUUc/

狼性发作 2024-10-20 06:37:22
<input type="checkbox" checked="checked" onclick="this.checked=true" />

我从问题开始:“如何发布/提交禁用的输入复选框?”在我的回答中,我跳过了评论:“如果我们想禁用一个复选框,我们肯定需要保留一个前缀值(选中或未选中),并且我们希望用户意识到它(否则我们应该使用隐藏类型和不是复选框)”。在我的回答中,我认为我们希望始终选中一个复选框,并且代码以这种方式工作。如果我们单击该复选框,它将永远被选中,并且其值将被发布/提交!同样的,如果我写
onclick="this.checked=false" 没有checked="checked" (注意:默认为未选中)它将永远处于未选中状态,并且其值将不会被发布/提交!。

<input type="checkbox" checked="checked" onclick="this.checked=true" />

I started from the problem: "how to POST/Submit an Input Checkbox that is disabled?" and in my answer I skipped the comment: "If we want to disable a checkbox we surely need to keep a prefixed value (checked or unchecked) and also we want that the user be aware of it (otherwise we should use a hidden type and not a checkbox)". In my answer I supposed that we want to keep always a checkbox checked and that code works in this way. If we click on that ckeckbox it will be forever checked and its value will be POSTED/Submitted! In the same way if I write
onclick="this.checked=false" without checked="checked" (note: default is unchecked) it will be forever unchecked and its value will be not POSTED/Submitted!.

时光倒影 2024-10-20 06:37:22

不要禁用它;相反,将其设置为只读,尽管这没有任何效果,因为不允许用户更改状态。但是您可以使用 jQuery 来强制执行此操作(防止用户更改复选框的状态:

$('input[type="checkbox"][readonly="readonly"]').click(function(e){
    e.preventDefault();
});

这假设您不想修改的所有复选框都具有“只读”属性。例如

<input type="checkbox" readonly="readonly">

Don't disable it; instead set it to readonly, though this has no effect as per not allowing the user to change the state. But you can use jQuery to enforce this (prevent the user from changing the state of the checkbox:

$('input[type="checkbox"][readonly="readonly"]').click(function(e){
    e.preventDefault();
});

This assumes that all the checkboxes you don't want to be modified have the "readonly" attribute. eg.

<input type="checkbox" readonly="readonly">
奶气 2024-10-20 06:37:22

这就像一个魅力:

  1. 删除“禁用”属性
  2. 提交表单
  3. 再次添加属性。最好的方法是使用 setTimeOut 函数,例如延迟 1 毫秒。

唯一的缺点是提交时禁用的输入字段会短暂闪烁。至少在我的场景中这不是什么大问题!

$('form').bind('submit', function () {
  var $inputs = $(this).find(':input'),
      disabledInputs = [],
      $curInput;

  // remove attributes
  for (var i = 0; i < $inputs.length; i++) {
    $curInput = $($inputs[i]);

    if ($curInput.attr('disabled') !== undefined) {
      $curInput.removeAttr('disabled');
      disabledInputs.push(true);
    } else 
      disabledInputs.push(false);
  }

  // add attributes
  setTimeout(function() {
    for (var i = 0; i < $inputs.length; i++) {

      if (disabledInputs[i] === true)
        $($inputs[i]).attr('disabled', true);

    }
  }, 1);

});

This works like a charm:

  1. Remove the "disabled" attributes
  2. Submit the form
  3. Add the attributes again. The best way to do this is to use a setTimeOut function, e.g. with a 1 millisecond delay.

The only disadvantage is the short flashing up of the disabled input fields when submitting. At least in my scenario that isn´t much of a problem!

$('form').bind('submit', function () {
  var $inputs = $(this).find(':input'),
      disabledInputs = [],
      $curInput;

  // remove attributes
  for (var i = 0; i < $inputs.length; i++) {
    $curInput = $($inputs[i]);

    if ($curInput.attr('disabled') !== undefined) {
      $curInput.removeAttr('disabled');
      disabledInputs.push(true);
    } else 
      disabledInputs.push(false);
  }

  // add attributes
  setTimeout(function() {
    for (var i = 0; i < $inputs.length; i++) {

      if (disabledInputs[i] === true)
        $($inputs[i]).attr('disabled', true);

    }
  }, 1);

});
浅浅淡淡 2024-10-20 06:37:22

因为:

  • 根据 HTML 规范,将只读属性设置为复选框是无效的,
  • 使用隐藏元素提交值不是很好的方式,并且
  • 设置阻止更改值的 onclick JavaScript 也不是很好

我将为您提供另一个可能性:

将您的复选框设置为正常禁用。在用户提交表单之前,通过 JavaScript 启用此复选框。

<script>
    function beforeSumbit() {
        var checkbox = document.getElementById('disabledCheckbox');
        checkbox.disabled = false;
    }
</script>
...
<form action="myAction.do" method="post" onSubmit="javascript: beforeSubmit();">
    <checkbox name="checkboxName" value="checkboxValue" disabled="disabled" id="disabledCheckbox" />
    <input type="submit />
</form>

由于该复选框在提交表单之前启用,因此其值以常见方式发布。该解决方案唯一不太令人愉快的是该复选框会启用一段时间并且用户可以看到。但这只是我可以忍受的一个细节。

Since:

  • setting readonly attribute to checkbox isn't valid according to HTML specification,
  • using hidden element to submit value isn't very pretty way and
  • setting onclick JavaScript that prevents from changing value isn't very nice too

I'm gonna offer you another possibility:

Set your checkbox as disabled as normal. And before the form is submitted by user enable this checkbox by JavaScript.

<script>
    function beforeSumbit() {
        var checkbox = document.getElementById('disabledCheckbox');
        checkbox.disabled = false;
    }
</script>
...
<form action="myAction.do" method="post" onSubmit="javascript: beforeSubmit();">
    <checkbox name="checkboxName" value="checkboxValue" disabled="disabled" id="disabledCheckbox" />
    <input type="submit />
</form>

Because the checkbox is enabled before the form is submitted, its value is posted in common way. Only thing that isn't very pleasant about this solution is that this checkbox becomes enabled for a while and that can be seen by users. But it's just a detail I can live with.

苄①跕圉湢 2024-10-20 06:37:22

除了隐藏字段之外没有其他选项,因此请尝试使用隐藏字段,如下面的代码所示:

<input type="hidden" type="text" name="chk1[]" id="tasks" value="xyz" >
<input class="display_checkbox" type="checkbox" name="chk1[]" id="tasks" value="xyz" checked="check"  disabled="disabled" >Tasks

There is no other option other than a hidden field, so try to use a hidden field like demonstrated in the code below:

<input type="hidden" type="text" name="chk1[]" id="tasks" value="xyz" >
<input class="display_checkbox" type="checkbox" name="chk1[]" id="tasks" value="xyz" checked="check"  disabled="disabled" >Tasks
一萌ing 2024-10-20 06:37:22

不幸的是,没有“简单”的解决方案。 readonly 属性不能应用于复选框。我阅读了有关复选框的 W3 规范,发现了罪魁祸首:

如果提交表单时控件没有当前值,则用户代理不需要将其视为成功的控件。http://www.w3.org/TR/html401 /interact/forms.html#h-17.13.2)

这会导致未选中状态和禁用状态产生相同的解析值。

  • readonly="readonly" 不是复选框的有效属性。
  • onclick="event.preventDefault();"并不总是一个好的解决方案,因为它是在复选框本身上触发的。但在某些场合它可以发挥魅力。
  • 启用 onSubmit 复选框并不是一个解决方案,因为该控件仍未被视为成功的控件,因此不会解析该值。
  • 在 HTML 中添加另一个同名的隐藏输入不起作用,因为第一个控件值会被第二个同名的控件值覆盖。

唯一完全证明的方法是在提交表单时使用 javascript 添加同名的隐藏输入

您可以使用我为此制作的小片段:

function disabled_checkbox() {
  var theform = document.forms[0];
  var theinputs = theform.getElementsByTagName('input');
  var nrofinputs = theinputs.length;
  for(var inputnr=0;inputnr<nrofinputs;inputnr++) {
    if(theinputs[inputnr].disabled==true) {
      var thevalueis = theinputs[inputnr].checked==true?"on":"";
      var thehiddeninput = document.createElement("input");
      thehiddeninput.setAttribute("type","hidden");
      thehiddeninput.setAttribute("name",theinputs[inputnr].name);
      thehiddeninput.setAttribute("value",thevalueis);
      theinputs[inputnr].parentNode.appendChild(thehiddeninput);
    }
  }
}

这会查找文档中的第一个表单,收集所有输入并搜索禁用的输入。当找到禁用的输入时,会在父节点中创建一个具有相同名称和值“on”(如果其状态为“已选中”)和“”(如果其状态为“” - 未选中)的隐藏输入。

该函数应由 FORM 元素中的事件“onsubmit”触发,如下所示:

<form id='ID' action='ACTION' onsubmit='disabled_checkbox();'>

Unfortunately there is no 'simple' solution. The attribute readonly cannot be applied to checkboxes. I read the W3 spec about the checkbox and found the culprit:

If a control doesn't have a current value when the form is submitted, user agents are not required to treat it as a successful control. (http://www.w3.org/TR/html401/interact/forms.html#h-17.13.2)

This causes the unchecked state and the disabled state to result in the same parsed value.

  • readonly="readonly" is not a valid attribute for checkboxes.
  • onclick="event.preventDefault();" is not always a good solution as it's triggered on the checkbox itself. But it can work charms in some occasions.
  • Enabling the checkbox onSubmit is not a solution because the control is still not treated as a successful control so the value will not be parsed.
  • Adding another hidden input with the same name in your HTML does not work because the first control value is overwritten by the second control value as it has the same name.

The only full-proof way to do this is to add a hidden input with the same name with javascript on submitting the form.

You can use the small snippet I made for this:

function disabled_checkbox() {
  var theform = document.forms[0];
  var theinputs = theform.getElementsByTagName('input');
  var nrofinputs = theinputs.length;
  for(var inputnr=0;inputnr<nrofinputs;inputnr++) {
    if(theinputs[inputnr].disabled==true) {
      var thevalueis = theinputs[inputnr].checked==true?"on":"";
      var thehiddeninput = document.createElement("input");
      thehiddeninput.setAttribute("type","hidden");
      thehiddeninput.setAttribute("name",theinputs[inputnr].name);
      thehiddeninput.setAttribute("value",thevalueis);
      theinputs[inputnr].parentNode.appendChild(thehiddeninput);
    }
  }
}

This looks for the first form in the document, gathers all inputs and searches for disabled inputs. When a disabled input is found, a hidden input is created in the parentNode with the same name and the value 'on' (if it's state is 'checked') and '' (if it's state is '' - not checked).

This function should be triggered by the event 'onsubmit' in the FORM element as:

<form id='ID' action='ACTION' onsubmit='disabled_checkbox();'>
氛圍 2024-10-20 06:37:22

您可以根据需要将其保持禁用状态,然后在提交表单之前删除禁用属性。

$('#myForm').submit(function() {
    $('checkbox').removeAttr('disabled');
});

You can keep it disabled as desired, and then remove the disabled attribute before the form is submitted.

$('#myForm').submit(function() {
    $('checkbox').removeAttr('disabled');
});
三生殊途 2024-10-20 06:37:22

onsubmit="this['*nameofyourcheckbox*'].disabled=false" 添加到表单中。

Add onsubmit="this['*nameofyourcheckbox*'].disabled=false" to the form.

终难愈 2024-10-20 06:37:22

添加 onclick="this.checked=true"解决我的问题:
例子:

<input type="checkbox" id="scales" name="feature[]" value="scales" checked="checked" onclick="this.checked=true" />

Adding onclick="this.checked=true"Solve my problem:
Example:

<input type="checkbox" id="scales" name="feature[]" value="scales" checked="checked" onclick="this.checked=true" />
审判长 2024-10-20 06:37:22

我只是在此处的答案中结合了 HTML、JS 和 CSS 建议

HTML:

<input type="checkbox" readonly>

jQuery:

(function(){
    // Raj: https://stackoverflow.com/a/14753503/260665
    $(document).on('click', 'input[type="checkbox"][readonly]', function(e){
        e.preventDefault();
    });
})();

CSS:

input[type="checkbox"][readonly] {
  cursor: not-allowed;
  opacity: 0.5;
}

由于该元素没有“禁用”,它仍然会通过 POST。

I just combined the HTML, JS and CSS suggestions in the answers here

HTML:

<input type="checkbox" readonly>

jQuery:

(function(){
    // Raj: https://stackoverflow.com/a/14753503/260665
    $(document).on('click', 'input[type="checkbox"][readonly]', function(e){
        e.preventDefault();
    });
})();

CSS:

input[type="checkbox"][readonly] {
  cursor: not-allowed;
  opacity: 0.5;
}

Since the element is not 'disabled' it still goes through the POST.

堇色安年 2024-10-20 06:37:22
<html>
    <head>
    <script type="text/javascript">
    function some_name() {if (document.getElementById('first').checked)      document.getElementById('second').checked=false; else document.getElementById('second').checked=true;} 
    </script>
    </head>
    <body onload="some_name();">
    <form>
    <input type="checkbox" id="first" value="first" onclick="some_name();"/>first<br/>
    <input type="checkbox" id="second" value="second" onclick="some_name();" />second
    </form>
    </body>
</html>

函数 some_name 是前一个子句的示例,用于根据子句管理第二个复选框,该复选框已选中(发布其值)或未选中(不发布其值),并且用户无法修改其状态;无需管理第二个复选框的任何禁用

<html>
    <head>
    <script type="text/javascript">
    function some_name() {if (document.getElementById('first').checked)      document.getElementById('second').checked=false; else document.getElementById('second').checked=true;} 
    </script>
    </head>
    <body onload="some_name();">
    <form>
    <input type="checkbox" id="first" value="first" onclick="some_name();"/>first<br/>
    <input type="checkbox" id="second" value="second" onclick="some_name();" />second
    </form>
    </body>
</html>

Function some_name is an example of a previous clause to manage the second checkbox which is checked (posts its value) or unchecked (does not post its value) according to the clause and the user cannot modify its status; there is no need to manage any disabling of second checkbox

梦里寻她 2024-10-20 06:37:22

这是可以从后端控制的另一种解决方法。

ASPX

<asp:CheckBox ID="Parts_Return_Yes" runat="server" AutoPostBack="false" />

在 ASPX.CS

Parts_Return_Yes.InputAttributes["disabled"] = "disabled";
Parts_Return_Yes.InputAttributes["class"] = "disabled-checkbox";

类中仅出于样式目的而添加。

Here is another work around can be controlled from the backend.

ASPX

<asp:CheckBox ID="Parts_Return_Yes" runat="server" AutoPostBack="false" />

In ASPX.CS

Parts_Return_Yes.InputAttributes["disabled"] = "disabled";
Parts_Return_Yes.InputAttributes["class"] = "disabled-checkbox";

Class is only added for style purposes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文