[英]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.