[英]Enable button if radio button selected
我已經嘗試了幾乎所有這里提到的方法和其他網站,但我仍然被卡住,所以這就是我在這里問的原因。
我已經在這個表單中創建了一個表單(帶有<form></form>
標簽)我正在創建4個無線電按鈕,使用從數據庫中提取的while循環數據。
要發送數據我正在使用綁定到按鈕單擊事件的JavaScript(Ajax)。
現在我想保持提交按鈕被禁用,直到所有字段都填滿了最后一個字段是單選按鈕我試圖使用許多其他方法來做到這一點但沒有發生任何事情,所以下面的任何方式是我正在使用的代碼。
function checkUrole() {
var roles = document.getElementById("userRoles"),
btn = document.getElementById("submit"),
len = roles.length,
sel = null;
for(var i=0; i < len; i++){
if (roles.checked){
sel = roles[i].value;
}
}
if (sel === null){
document.getElementById("msgID").innerHTML = "9";
btn.disabled = true;
}else{
btn.disabled = false;
}
}
這是我的HTML
<label for="userRoles">User Role:</label><br>
<?php while ($row = $getUserRoleQuery -> fetch(PDO::FETCH_ASSOC)) { ?>
<input type="radio" id="userRoles" name="userRoles" value="<?php echo $row["urId"]; ?>" onmousedown="checkUrole()"><?php echo $row["userRole"]; }?>
<label id="msgID" hidden></label>
<div id="msg"></div>
基本上HTML會創建這樣的東西,
<input type="radio" id="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
<input type="radio" id="userRoles" name="userRoles" value="2" onmousedown="checkUrole()">Manager
<input type="radio" id="userRoles" name="userRoles" value="3" onmousedown="checkUrole()">Team Leader
<input type="radio" id="userRoles" name="userRoles" value="4" onmousedown="checkUrole()">User
我不喜歡寫這樣的代碼,
if(document.getElementById("userRoles1").checked{
something here;
}else if(document.getElementById("userRoles2").checked{
something here;
}else{
something here;
}
上面我認為如果添加一個新的用戶角色,會使程序變得不那么動態我會在循環中添加一個新的IF。
那么我有什么方法可以解決這個問題,如果可以,我喜歡使用JavaScript。
更新:感謝@ zer00ne我解決了這個問題,下面是壓軸工作代碼,希望這對未來的任何人都有幫助。
我的HTML:
<script language="JavaScript" type="text/javascript" src="../jScripts/userCreatFunctions.js">
<div id="userRoles">
<input type="radio" name="userRoles" value="1" checked>Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
我的JaveScript:
$(document).ready(function () {
/*Register the change element to #roles
|| When clicked...*/
//This code base was originally developed by zer00ne I'm using it under his permission
//Thanks man.
var form = document.getElementById('userRoles');
if (form){
form.addEventListener('change', function(e) {
/* Determine if the e.target (radio that's clicked)
|| is NOT e.currentTarget (#roles)
*/
if (e.target !== e.currentTarget) {
// Assign variable to e.target
var target = e.target;
// Reference the submit button
var btn = document.querySelector('[name=submit]');
// Enable submit button
btn.disabled = false;
// call rolrDist() passing the target,value
roleDist(target.value);
}
}, false);
}
function roleDist(rank) {
var display = document.getElementById("msg");
if (rank !== null) {
display.innerHTML = "All done! You can save";
} else {
display.innerHTML = "Please Select User Type";
}
}
});
使用$(document).ready(function () {})
其他方式在DOM之前加載腳本,這導致NULL值使腳本無法運行。
首先,您不需要每個輸入元素上的id
。 您可以使用getElementsByName
按名稱獲取按鈕元素的數組,下面是一個示例,說明如何基於其中一個被檢查來執行“某事”:
JS (使用ES6)
const getRadioValue = (name) => {
const radios = document.getElementsByName(name);
let val;
Object.keys(radios).forEach((obj, i) => {
if (radios[i].checked) {
val = radios[i].value;
}
});
return val;
}
document.getElementById('form').addEventListener('change', (e) => {
getRadioValue('userRoles'); // value of checked radio button.
});
HTML
<div id="form">
<input type="radio" name="userRoles" value="1">Admin
<input type="radio" name="userRoles" value="2">Manager
<input type="radio" name="userRoles" value="3">Team Leader
<input type="radio" name="userRoles" value="4">User
</div>
一個更有效的方法是使用Array.prototype.find()方法,這更好,因為:
find方法為數組的每個索引執行一次回調函數,直到找到一個回調返回true值的回調函數。 如果找到這樣的元素,find會立即返回該元素的值。
換句話說,一旦我們找到了我們想要它返回的內容,它就不需要迭代整個Array
。
注意:使用上面提到的change
事件中的以下代碼段來檢索選中的值。
JS (使用ES6)
const getCheckedRadioValue = (name) => {
const radios = document.getElementsByName(name);
try {
// calling .value without a "checked" property will throw an exception.
return Array.from(radios).find((r, i) => radios[i].checked).value
} catch(e) { }
}
getCheckedRadioValue('userRoles');
JS (沒有ES6)
function getCheckedRadioValue(name) {
var radios = document.getElementsByName(name);
var val;
for (var i = 0, len = radios.length; i < len; i++) {
if (radios[i].checked) {
val = radios[i].value;
break;
}
}
return val; // return value of checked radio or undefined if none checked
}
getCheckedRadioValue('userRoles');
參考
不完全確定你要做什么,所以這是我猜的:
需要確定已檢查無線電輸入的值
需要啟用由已檢查的無線電確定的提交按鈕
需要有效地調用其他功能,運行其他交互等,具體取決於具體檢查的內容。
詳細信息在Snippet中進行了注釋
SNIPPET
// Reference #roles var form = document.getElementById('roles'); /* Register the change element to #roles || When clicked... */ form.addEventListener('change', function(e) { /* Determine if the e.target (radio that's clicked) || is NOT e.currentTarget (#roles) */ if (e.target !== e.currentTarget) { // Assign variable to e.target var target = e.target; // Find the textNode next to target var label = target.nextSibling; // Reference the #display var display = document.getElementById('display'); // Display the <label>s text and radio value display.value = label.textContent + ' - Rank: ' + target.value; // Reference the submit button var btn = document.querySelector('[type=submit]'); // Enable submit button btn.disabled = false; // call rolrDist() passing the target,value roleDist(target.value); } }, false); function roleDist(rank) { switch (rank) { case '4': alert('Rank 4 - Limited Access'); // Take user to landing page break; case '3': alert('Rank 3 - Basic Access'); // Take user to dashboard break; case '2': alert('Rank 2 - Advanced Access'); // Take user to database break; case '1': alert('Rank 1 - Full Access'); // Take user to admin panel break; } }
input, output, [type=submit] { font: inherit; cursor: pointer; } [type=submit] { float: right; }
<form id='roles'> <input type="radio" name="role" value="1">Admin <input type="radio" name="role" value="2">Manager <input type="radio" name="role" value="3">Team Leader <input type="radio" name="role" value="4">User </form> <br/> <label for='display'>Role: </label> <!-- Since #display and submit button are outside of the <form>, using the form attribute and the <form>'s #id as the value establishes an association between them and <form> --> <output id='display' form='roles'></output> <br/> <input type='submit' form='roles' disabled>
您的標記中存在非常基本的錯誤,您不應該使用具有相同ID的元素
您可以使用class而不是id( 將類賦予radioboxes )
document.getElementsByClassName( “的UserRole”)
<input type="radio" class="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin
其余的代碼似乎沒問題
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.