[英]How to alternate between read-only and input mode using the "value" property of <input> element
I am trying to make a webpage full of <input>
tags, where one can switch between edit and read-only modes.我正在尝试制作一个充满<input>
标签的网页,您可以在其中在编辑和只读模式之间切换。 How can I do that easily, my guess being using the value attribute of <input>
?我怎么能轻松做到这一点,我的猜测是使用<input>
的 value 属性?
You can create a state variable isEditMode=true
and create a button that changes the state values to true or false.您可以创建一个状态变量isEditMode=true
并创建一个将状态值更改为 true 或 false 的按钮。 Now you can use this variable and pass it's value as disabled attribute like this:-现在您可以使用此变量并将其值作为禁用属性传递,如下所示:-
<input disabled={!isEditMode}/>
So if it not in edit mode then input will be disabled or we can say in view mode.因此,如果它不在编辑模式下,那么输入将被禁用,或者我们可以说在查看模式下。
Here is a small example of how you can create a class that will automatically generate inputs and update them to readonly whenever you want.这是一个小示例,说明如何创建一个类,该类将自动生成输入并在需要时将它们更新为只读。 (on the fiddle there is a working example of it) . (在小提琴上有一个工作示例) 。 Just connect a button to update the input to只需连接一个按钮即可将输入更新为
Εdit: this solution is best suited for use in vanilla js编辑:此解决方案最适合在 vanilla js 中使用
https://jsfiddle.net/0hvjr2uL/25/ https://jsfiddle.net/0hvjr2uL/25/
class Inp {
constructor(name, value, placeholder, id, readOnly = false) {
this.name = name;
this.value = value;
this.placeholder = placeholder;
this.id = id;
this.readOnly = readOnly;
}
render(root){
let input = document.createElement("input");
input.name = this.name;
input.value = this.value
input.id = this.id;
input.setAttribute("readonly", this.readOnly);
root.appendChild(input);
}
update() {
let input = document.getElementById(this.id);
input.setAttribute("readonly", this.readOnly);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.