问题 输入字段禁用,直到选中单选按钮(HTML)


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

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

这是我的代码:

        <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>

10068
2017-09-19 08:50


起源

您将无法仅使用纯HTML执行此操作。您需要集成javascript。 - andy


答案:


你需要使用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>


13
2017-09-19 09:02



如果我需要在开始时选中复选框并禁用该怎么办 id="charstype" 在onclick事件执行之前
@ Mr.Shrestha使用 disabled="disabled" HTML属性默认情况下禁用任何输入而不执行任何事件。要在开头选中复选框,您还可以使用HTML属性 checked="checked" - Wilq


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

<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>​​​​​​​​​​​

你可以看到它的工作原理 这里


2
2017-09-19 09:02



当您在单选按钮之间切换时,小提琴不起作用 - orjan