【问题标题】:How to disable html input readonly if user select that option?如果用户选择该选项,如何以只读方式禁用 html 输入?
【发布时间】:2020-06-06 14:57:41
【问题描述】:

默认情况下,输入区域设置为只读。现在我希望如果用户选择了选择 3,则输入区域现在可以输入文本。我该怎么做?

<div class="form-group">
<label for="selections">Options:</label>
<select class="form-control" id="selections" required>
<option value="sel1">
Selection 1</option>
<option value="sel2">
Selection 2</option>
<option value="sel3">
Selection 3</option>
</select>
</div>
<label for="textsection">Text to be edit:</label>
<input type="text" class="form-control" id="textsection" maxlength="34" 
placeholder="User can type here if he select option 3" readonly>

【问题讨论】:

  • 我会说使用 javascript 你可以在if 语句中使用removeAttribute() 方法来删​​除只读。做一些研究,让我们知道你尝试了什么。不要只要求我们为您编写代码。

标签: html readonly


【解决方案1】:

您需要使用 Javascript,选择元素(选择和输入),在您的选择元素上添加事件侦听器,然后您可以创建一个函数来处理此行为。试试这样的:

const select = document.querySelector("#selections");
const text = document.querySelector("#textsection");
select.addEventListener("change", handleSelectChange);

function handleSelectChange(event) {
    const value = event.target.value;
    value === 'sel3' ? text.readOnly = false : text.readOnly = true;
}

您必须将此脚本包含在您的 HTML 文件中。

【讨论】:

    猜你喜欢
    • 2023-03-08
    • 2017-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-21
    • 2011-09-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多