我有一个复杂的表单,有许多选项,其状态(启用/禁用)取决于其他一些控件的值,因此可能会在提交表单时禁用这些选项(并且未发布选择值)。 即使在不允许用户更改选择的情况下,我也需要发布所选值。
我在这里看到了一些解决方案HTML表单只读SELECT标签/输入 (主要解决方案是将一个隐藏字段与禁用的select同步)。
我想采取一种稍微不同的方法:我想使用knockout(已在项目中使用)仅在数据可编辑时显示选择,否则显示只读输入(或div / span)。
如何使用knockout来简化这种方法?
I have a complex form with many selects whose state (enabled/disabled) depends on the value of some other controls, so it could happen that these selects are disabled when submitting the form (and the select value is not posted). I need to post the selected value even in the case the user is not allowed to change the select.
I saw some solutions here HTML form readonly SELECT tag/input (mainly the solution is to have an hidden field synchronized with the disabled select).
I am thinking to taking a slightly different approach: I want to use knockout (already used in the project) to display the select only when the data is editable, and display a readonly input (or a div/span) otherwise.
How can I use knockout to simplify this approach?
最满意答案
简单地禁用选择就足以阻止它发布 - 您不必将其设为只读。 这实际上很简单。 使用attr绑定,您可以有条件地应用属性。 所以你需要的是一个observable,它为select提供一个布尔状态:
在您的视图模型中
self.DisableSelects = ko.observable(false);你的选择绑定
attr: { disabled: DisableSelects }然后,当您希望禁用任何类似绑定的选择时,您只需将observable设置为true:
viewModel.DisableSelects(true)显然,如果你想要更大的粒度,你只需创建更多这样的observable并适当绑定。
编辑
你的问题没有明确说明你真正想要的是什么,但我觉得问题是你实际上确实希望发布的值即使被禁用了。 在此,我必须同意关联问题的第一个答案:不要依赖于那里的公布价值。 只读或禁用字段不会阻止更改值。 每个现代浏览器都内置了开发工具,让您可以在适当的位置更改HTML(即删除只读或禁用的标志),任何拥有HTML基本知识的人都可以将其删除。 如果你想要一个只读字段,那么唯一安全的方法就是完全忽略发布的值。 你可以用隐藏的输入做各种各样的技巧,但也可以轻松搞定。
In my viewModel I define the property relative to the state of the select, the property bounded to the select value and a computed observable that "reads" the description of the selected option in the select:
AppViewModel: function () { var self = this; self.SelectVisible = ko.computed(function () { return true; // return true or false depending on your context }, self); self.Category = ko.observable(""); self.CategoryText = ko.computed(function () { return $("#Category option[value='" + self.Category() + "']").text(); }, self); // other code ... }In the page I have a select always enabled and a readonly input whose visibility is mutually esclusive and depends on a viewModel property:
<select name="Category" id="Category" data-bind="value: Category, visible: SelectVisible"> <option value="S">Standard</option> <option value="N">CatN</option> <option value="C">CatC</option> </select> <input style="display: none;" type="text" readonly="readonly" data-bind="value: CategoryText, visible: !SelectVisible()"/>更多推荐
发布评论