2012-09-19 115 views
10

我有兩個字段,其中一個是文本輸入字段,另一個是選擇標籤。 事情是我希望其中一個只能啓用 ,用戶應該通過點擊上面的單選按鈕來選擇啓用哪一個。輸入字段禁用,直到選中單選按鈕(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> 
+0

您將無法只用純HTML完成此操作。你將需要整合JavaScript。 – andy

回答

10

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

+0

如果我需要在開始時檢查複選框,並在執行onclick事件之前禁用'id =「charstype」',那麼該怎麼辦 – 2016-03-01 10:00:04

+0

@ Mr.Shrestha使用'disabled =「disabled」'HTML屬性默認禁用任何輸入而沒有任何事件執行。要使複選框在開始時被選中,您還可以使用HTML屬性checked =「checked」' – Wilq

1

我修改了代碼,做你想做的,那就是:

<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

+0

當您在單選按鈕之間切換時,小提琴不起作用 – orjan