[英]Enabling Disabling Text Fields using PHP when a radio button is clicked
我有 2 個單選按鈕(啟用/禁用)和 3 個文本框。 如果單擊禁用單選按鈕,我想禁用 3 個文本框。
<Input type = 'Radio' Name ='target' value= 'r1'>Enable
<Input type = 'Radio' Name ='target' value= 'r2'>Disable
T1: <input type="text" name="t1">
T2: <input type="text" name="t2">
T3: <input type="text" name="t3">
一旦我選擇了一個單選按鈕,就會發生這種變化。 我正在使用 PHP。 蒂亞!
盡管使用 jQuery 會更容易,但以下是純粹在 JavaScript 中執行此操作的一種方法:
let textboxes = document.querySelectorAll('input[type=text]'); document.querySelectorAll('input[name=target]') .forEach(function(radio) { radio.addEventListener('change', function(e) { let value = e.target.value; if (value === 'r1') { textboxes .forEach(function(textbox) { textbox.disabled = false; }); } else if (value === 'r2') { textboxes .forEach(function(textbox) { textbox.disabled = true; }); } }); });
<Input type='Radio' Name='target' value='r1'>Enable <Input type='Radio' Name='target' value='r2'>Disable <br><br> T1: <input type="text" name="t1"> T2: <input type="text" name="t2"> T3: <input type="text" name="t3">
它基本上偵聽單選按鈕的change
事件,並通過文本框循環以啟用/禁用它們。
$('.radio').click(function(e) { var val = $(this).val(); if(val=="r2") $('input[type="text"]').attr('disabled','disabled'); else $('input[type="text"]').removeAttr('disabled'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label><Input class="radio" type = 'Radio' checked Name ='target' value= 'r1'>Enable </label> <label><Input class="radio" type = 'Radio' Name ='target' value= 'r2'>Disable </label><br /><br /> T1: <input type="text" name="t1"> T2: <input type="text" name="t2"> T3: <input type="text" name="t3">
根據我的評論,這是代碼。 將 jquery 代碼與其他文本框一起使用。 確保您應該在代碼頂部包含 jquery 庫
$(document).ready(function() { $("#enable").click(function() { $("#t1").attr("disabled", false); }); $("#disable").click(function() { $("#t1").attr("disabled", true); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!DOCTYPE html> <html> <head> <meta charset=utf-8 /> <title>JS Bin</title> </head> <body> <Input type = 'Radio' Name ='target' value= 'r1' id="enable">Enable <Input type = 'Radio' Name ='target' value= 'r2' id="disable">Disable T1: <input type="text" name="t1" id="t1"> </body> </html>
好吧,當您使用 PHP(一種服務器端語言)時,每當您單擊radiobutton,
刷新頁面, radiobutton
就會回到未選中狀態。 因此,為此,您必須使用 JavaScript,而 jquery 是處理 DOM 元素的最佳方式。 您需要再添加幾行代碼。 不要忘記在 HTML 的 ` 標記中添加 jQuery。
<script type="text/javascript">
$(document).ready(function () {
$("#enable").click(function () {
$("#t1").attr("disabled", true);
});
$("#disable").click(function () {
$("#t1").attr("disabled", false);
});
});
</script>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.