Is there any way to disable a bunch of form elemen

2019-03-11 02:55发布

I'd like to disable a section of HTML form elements depending on some conditions. This seems to be the ideal way to do that:

<fieldset disabled>
    <input value="one" />
    <input value="two" />
</fieldset>

Now, those two inputs are disabled. However, this seems to be totally borked on IE8. The inputs appear disabled but I can still type in them.

Fiddle (Not as if JsFiddle actually works in IE8)

Is there a cross-browser solution for this problem, without adding disabled to every form element (which would complicate my script). I could probably do something tricky like select the <fieldset> in jQuery, then .each() through all the form elements and disable them - however, I'm actually setting the disabled attribute using a Knockout binding so there's really no place to add such code. My last resort is to use a custom Knockout binding that disables all the children too, but le sigh.

5条回答
时光不老,我们不散
2楼-- · 2019-03-11 03:03

Give the id to your fieldset tag(or u can also use tag name directly in jquery code) & use following code to make all the fields disable in that fieldset using jquery.

$("#fieldset id" or "fieldset").children().attr("disabled", "disabled");

查看更多
\"骚年 ilove
3楼-- · 2019-03-11 03:07

In short: No. The reason behind this is because the lack of support in IE8 and the disabled attribute on the fieldset element.

Source

In IE7 and IE8, the attribute only disables form elements in the < legend >.

I'm afraid you should look for a custom solution like the answers from other users / your own custom binding.

查看更多
萌系小妹纸
4楼-- · 2019-03-11 03:16

Solution using jQuery:

var disabledFiedset=$('fieldset[disabled]');
$('input',disabledFiedset).attr('disabled','disabled');
查看更多
贪生不怕死
5楼-- · 2019-03-11 03:22

Ok, I've come up with a Knockout.js specific implementation that hopefully will help some other people in the same boat. This solution could probably be adapted for other solutions and platforms with a little effort.

First, I created a Knockout binding:

ko.bindingHandlers.allowEdit = {
   init: function(element, valueAccessor)
   {
      if(!valueAccessor())
      {
         element.disabled = true;
         element.readOnly = true;

         if(element.tagName === 'FIELDSET')
         {
            $(':input', element).attr('disabled', 'disabled');
         }
      }
   }
};

Note, you'd have to implement the update method too if you wanted to allow changes to this binding. I didn't have this requirement.

You could then use the binding as such:

<fieldset data-bind="allowEdit: someExpression">
   <input value="One" />
   <input value="Two" />
</fieldset>
查看更多
Animai°情兽
6楼-- · 2019-03-11 03:30

I was able to do something similar using an observable in my model called editable and then in my input I used a data-bind="enable: editable” and this totally works in IE 7, 8 and 9.

查看更多
登录 后发表回答