【问题标题】:input field disabled until radio button is checked (HTML)在选中单选按钮之前禁用输入字段(HTML)
【发布时间】:2012-09-11 13:27:03
【问题描述】:

我有两个字段,一个是文本输入字段,另一个是选择标签。 问题是我只想启用其中一个 并且用户应该通过单击上面的单选按钮之一来选择启用哪一个。

因此,如果用户选择第一个单选按钮,输入字段将被启用 如果他选择第二个,则选择标签将被启用。

这是我的代码:

        <input type="radio" name="type" value="customurl">wanna custom url?
        <input type="text" name="custom" placeholder="should be 5 charecters at least" >
        <br><br>
        <input type="radio" name="type" value="customurl">random?
        <select name="charstype">
            <option>Letters</option>
            <option>Number</option>
        </select>

【问题讨论】:

  • 您无法仅在纯 HTML 中执行此操作。您将需要集成 javascript。

标签: javascript html html-select forms html-input


【解决方案1】:

您将需要使用 javascript。您给出的代码中最短的方法是将 ID 属性附加到选择和输入字段,并通过“onclick”事件禁用/启用它们。

<input onclick="document.getElementById('custom').disabled = false; document.getElementById('charstype').disabled = true;" type="radio" name="type" checked="checked">wanna custom url?
<input type="text" name="custom" id="custom" placeholder="should be 5 charecters at least" >
<br><br>
<input onclick="document.getElementById('custom').disabled = true; document.getElementById('charstype').disabled = false;" type="radio" name="type" value="customurl">random?
<select name="charstype" id="charstype" disabled="disabled">
       <option>Letters</option>
       <option>Number</option>
</select>

【讨论】:

  • 如果我需要在开头选中复选框并在执行 onclick 事件之前禁用 id="charstype" 该怎么办
  • @Mr.Shrestha 使用disabled="disabled" HTML 属性默认禁用任何输入而不执行任何事件。要在开头选中复选框,您还可以使用 HTML 属性 checked="checked"
【解决方案2】:

我修改了你的代码来做你想做的事,这里是:

<input type="radio" name="type" value="customurl" 
onclick="document.getElementById('text').removeAttribute('disabled')">wanna custom url?
<input type="text" id="text" name="custom" 
placeholder="should be 5 charecters at least" disabled>
<br><br>
<input type="radio" name="type" value="customurl" 
onclick="document.getElementById('sel').removeAttribute('disabled')">random?
<select id="sel" name="charstype" disabled>
    <option>Letters</option>
    <option>Number</option>
</select>​​​​​​​​​​​

你可以看到它在工作here

【讨论】:

  • 在单选按钮之间切换时小提琴不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-12-08
  • 2011-05-18
  • 2018-01-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多