web-dev-qa-db-ja.com

ラジオボタンがチェックされるまで入力フィールドは無効(HTML)

2つのフィールドがあります。1つはテキスト入力フィールドで、もう1つは選択タグです。問題は、そのうちの1つだけを有効にし、ユーザーは上記のラジオボタンのいずれかをクリックして、有効にするものを選択することです。

したがって、ユーザーが最初のラジオボタンを選択すると、入力フィールドが有効になり、2番目を選択すると、選択タグが有効になります。

これが私のコードです:

        <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>
12
Alex C.

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

あなたはそれが機能しているのを見ることができます here

2
Nelson