如何使输入字段为只读

时间:2018-07-04 03:30:39

标签: javascript html

我想使输入字段为只读。下面的代码为我工作。但是,如果刷新页面,则输入字段将变为只读,并且我无法在输入字段中输入任何内容。我希望只有在输入字段中存在数据后,它才能变为只读状态。

      const disableInputs = function() {
      sessionStorage.disableInputs = 'true';
      document.getElementById('firstname').disabled = true;
      document.getElementById('lastname').disabled = true;
      document.getElementById('email').disabled = true;
      document.getElementById('mew').disabled = true;
      };
      if (sessionStorage.disableInputs === 'true') disableInputs();
      document.getElementById('myButton').onclick = disableInputs;

非常感谢您的帮助。谢谢

3 个答案:

答案 0 :(得分:1)

使用此命令:document.getElementById("your-id").readOnly = true;

来源: https://www.w3schools.com/jsref/prop_text_readonly.asp

w3schools的片段: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_text_readonly2

function myFunction() {
    document.getElementById("myText").readOnly = true;
}
<!DOCTYPE html>
<html>
<body>

Name: <input type="text" id="myText">

<p>Click the button to set the text field to read-only.</p>

<p><strong>Tip:</strong> To see the effect, try to type something in the text field before and after clicking the button.</p>

<button onclick="myFunction()">Try it</button>

</body>
</html>

答案 1 :(得分:1)

在HTML中:

    int id = GetDlgCtrlID((HWND)lParam);

        // Obtain the control associated with the id.
    X3D::Windows::Control *ctrl = frm.getControls().at(id);
        if (ctrl == NULL)
            return 0;

        // Check if this is a X3D Label control. 
        Label *lbl = dynamic_cast<X3D::Windows::Label*>(ctrl);

        if (lbl != NULL)
        {
            SetTextColor((HDC)wParam, lbl->getForeColor());
            break;
        }   

在PHP中:

    int id = GetDlgCtrlID((HWND)lParam);

        // Obtain the control associated with the id.
    X3D::Windows::Control *ctrl = frm.getControls().find(id)->second;
        if (ctrl == NULL)
            return 0;

使用Javascript

    <record id="action_id" model="ir.actions.server">
                <field name="name">name</field>
                <field name="model_id" ref="module_name.model_object_name" />
                <field name="code">
                    action = model.function_name()
                </field>
            </record>

一起:

<input type="text" id="someid" name="somename" readonly="readonly" value="">

答案 2 :(得分:0)

您可以像html中所需的那样仅添加只读。