简体   繁体   English

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

[英]how to POST/Submit an Input Checkbox that is disabled?

I have a checkbox that, given certain conditions, needs to be disabled.我有一个复选框,在特定条件下,需要禁用该复选框。 Turns out HTTP doesn't post disabled inputs.结果证明 HTTP 没有发布禁用的输入。

How can I get around that?我怎样才能解决这个问题? submitting the input even if it's disabled and keeping the input disabled?提交输入即使它被禁用并保持输入禁用?

UPDATE : READONLY doesn't work on checkboxes更新READONLY不适用于复选框

You could use disabled="disabled" but at this point checkbox's value will not appear into POST values.您可以使用disabled="disabled"但此时复选框的值不会出现在POST值中。 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只需将disabled更改为readonly

I've solved that problem.我已经解决了那个问题。

Since readonly="readonly" tag is not working (I've tried different browsers), you have to use disabled="disabled" instead.由于readonly="readonly"标签不起作用(我尝试过不同的浏览器),您必须使用disabled="disabled"代替。 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 .要同时获得“只读”外观和POST复选框的值,只需添加一个与您的复选框具有相同名称和值的隐藏“输入” You have to keep it next to your checkbox or between the same <form></form> tags:你必须把它放在你的复选框旁边或相同的<form></form>标签之间:

<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!另外,只是为了让您知道readonly="readonly", readonly="true", readonly="",或仅READONLY无法解决此问题! 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这个参考也不相关(可能还没有,或者不再相关,我不知道): http : //www.w3schools.com/tags/att_input_readonly.asp

If you're happy using JQuery then remove the disabled attribute when submitting the form:如果您对使用 JQuery 感到满意,请在提交表单时删除 disabled 属性:

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

You could handle it this way... For each checkbox, create a hidden field with the same name attribute.你可以这样处理...对于每个复选框,创建一个具有相同name属性的隐藏字段。 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.您可以使用任何值而不是“false”,但您明白了。

create a css class eg:创建一个 css 类,例如:

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

apply this class instead of disabled attribute应用此类而不是禁用属性

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).此外,一旦满足某个条件(如果这就是您所追求的),您就可以使用 javascript 清除 onclick。 Here's a down-and-dirty fiddle showing what I mean.这是一个肮脏的小提琴,展示了我的意思。 It's not perfect, but you get the gist.这并不完美,但你明白了要点。

http://jsfiddle.net/vwUUc/ http://jsfiddle.net/vwUUc/

<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!如果我们点击那个 ckeckbox,它将永远被检查,它的值将被发布/提交! 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!.以同样的方式,如果我写 onclick="this.checked=false" 而没有 checked="checked"(注意:默认是未选中的),它将永远处于未选中状态,并且它的值不会被发布/提交!。

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, eg with a 1 millisecond delay.最好的方法是使用setTimeOut函数,例如延迟 1 毫秒。

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);

});

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:但是您可以使用 jQuery 来强制执行此操作(防止用户更改复选框的状态:

$('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">

Since:自从:

  • setting readonly attribute to checkbox isn't valid according to HTML specification,根据 HTML 规范,将只读属性设置为复选框无效,
  • 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设置防止更改值的 onclick JavaScript 也不是很好

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.在用户提交表单之前,通过 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.但这只是我可以接受的一个细节。

Unfortunately there is no 'simple' solution.不幸的是,没有“简单”的解决方案。 The attribute readonly cannot be applied to checkboxes.属性 readonly 不能应用于复选框。 I read the W3 spec about the checkbox and found the culprit:我阅读了有关复选框的 W3 规范并找到了罪魁祸首:

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 ) ( 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. readonly="readonly" 不是复选框的有效属性。
  • onclick="event.preventDefault();" 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.启用 onSubmit 复选框不是解决方案,因为该控件仍未被视为成功的控件,因此不会解析该值。
  • 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.在 HTML 中添加另一个具有相同名称的隐藏输入不起作用,因为第一个控件值被第二个控件值覆盖,因为它具有相同的名称。

The only full-proof way to do this is to add a hidden input with the same name with javascript on submitting the form .唯一完全证明的方法是在提交表单时添加一个与 javascript 同名的隐藏输入

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).当找到禁用的输入时,会在 parentNode 中创建一个具有相同名称和值 'on'(如果它的状态为 'checked')和 ''(如果它的状态为 '' - 未选中)的隐藏输入。

This function should be triggered by the event 'onsubmit' in the FORM element as:此函数应由 FORM 元素中的事件“onsubmit”触发,如下所示:

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

There is no other option other than a hidden field, so try to use a hidden field like demonstrated in the code below:除了hidden字段之外没有其他选项,因此请尝试使用如下代码所示的hidden字段:

<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

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

I just combined the HTML, JS and CSS suggestions in the answers here我只是在这里的答案中结合了 HTML、JS 和 CSS 建议

HTML: HTML:

<input type="checkbox" readonly>

jQuery: jQuery:

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

CSS: CSS:

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

Since the element is not 'disabled' it still goes through the POST.由于该元素未被“禁用”,它仍会通过 POST。

<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;函数 some_name 是前一个子句的示例,用于管理根据子句选中(发布其值)或未选中(不发布其值)且用户无法修改其状态的第二个复选框; there is no need to manage any disabling of second checkbox无需管理任何禁用第二个复选框

You can keep it disabled as desired, and then remove the disabled attribute before the form is submitted.您可以根据需要将其禁用,然后在提交表单之前删除禁用属性。

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

Adding onclick="this.checked=true" Solve my problem:添加onclick="this.checked=true"解决我的问题:
Example:例子:

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

Here is another work around can be controlled from the backend.这是可以从后端控制的另一种解决方法。

ASPX ASPX

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

In ASPX.CS在 ASPX.CS 中

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

Class is only added for style purposes.添加类仅用于样式目的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM