简体   繁体   English

如果选中单选按钮,则启用按钮

[英]Enable button if radio button selected

I've tried almost all the methods mentioned here and in other websites but still I'm stuck so that's why I'm asking it here. 我已经尝试了几乎所有这里提到的方法和其他网站,但我仍然被卡住,所以这就是我在这里问的原因。

I've created a form (with out <form></form> tags) in this form I'm creating 4 radios buttons using a while loop data is being pulled from a database. 我已经在这个表单中创建了一个表单(带有<form></form>标签)我正在创建4个无线电按钮,使用从数据库中提取的while循环数据。

To send data I'm using a JavaScript(Ajax) which is bound to a button click event. 要发送数据我正在使用绑定到按钮单击事件的JavaScript(Ajax)。

Now I want to keep the submit button disabled until all the filed's are filled the last filed's are the radio buttons I'm tried to use many other ways to do this but nothing happened so any way below is code I'm using. 现在我想保持提交按钮被禁用,直到所有字段都填满了最后一个字段是单选按钮我试图使用许多其他方法来做到这一点但没有发生任何事情,所以下面的任何方式是我正在使用的代码。

    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;
    }
}

And this is my HTML 这是我的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>

Basically the HTML will create something like this, 基本上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

I don't like write a code like this, 我不喜欢写这样的代码,

if(document.getElementById("userRoles1").checked{
something here;
}else if(document.getElementById("userRoles2").checked{
something here;
}else{
something here;
}

above I think makes the program a bit less dynamic 'cos if a new user role is added I've add a new IF to the loop. 上面我认为如果添加一个新的用户角色,会使程序变得不那么动态我会在循环中添加一个新的IF。

So is there any way I solve this and I like to use JavaScript if can. 那么我有什么方法可以解决这个问题,如果可以,我喜欢使用JavaScript。

UPDATE: Thanks to @zer00ne I solved this problem and below is the finale working code hope this helps any one in the future as well. 更新:感谢@ zer00ne我解决了这个问题,下面是压轴工作代码,希望这对未来的任何人都有帮助。

My HTML: 我的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>

My JaveScript: 我的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";
        }
    }
});

Use the $(document).ready(function () {}) other wise the script get loaded before the DOM which leads to a NULL value making the script none functional. 使用$(document).ready(function () {})其他方式在DOM之前加载脚本,这导致NULL值使脚本无法运行。

Firstly, you don't need the id 's on every input element. 首先,您不需要每个输入元素上的id You can get an array of the button element by name using getElementsByName , here is an example of how you would do "something" based on one of those being checked: 您可以使用getElementsByName按名称获取按钮元素的数组,下面是一个示例,说明如何基于其中一个被检查来执行“某事”:

JS (Using ES6) 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 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>

JsFiddle Example JsFiddle示例

UPDATE - improved 更新 - 改进

A more efficient method would be using the Array.prototype.find() method, this is better because: 一个更有效的方法是使用Array.prototype.find()方法,这更好,因为:

The find method executes the callback function once for each index of the array until it finds one where callback returns a true value. find方法为数组的每个索引执行一次回调函数,直到找到一个回调返回true值的回调函数。 If such an element is found, find immediately returns the value of that element. 如果找到这样的元素,find会立即返回该元素的值。

In other words, it doesn't need to iterate the entire Array , once we find what we want it returns. 换句话说,一旦我们找到了我们想要它返回的内容,它就不需要迭代整个Array

Note: Use the below snippets within the change event mentioned above to retrieve the checked value. 注意:使用上面提到的change事件中的以下代码段来检索选中的值。

JS (Using ES6) 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');

JsFiddle Example JsFiddle示例

JS (Without ES6) 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');

JsFiddle Example JsFiddle示例

References 参考

Not exactly sure what you are trying to do, so here is what I'm guessing: 不完全确定你要做什么,所以这是我猜的:

  • Need to determine the value of a checked radio input 需要确定已检查无线电输入的值

  • Need to enable a submit button that's determined by a checked radio 需要启用由已检查的无线电确定的提交按钮

  • Need to effectively call upon other functions, run additional interactions, etc. depending on what was specifically checked. 需要有效地调用其他功能,运行其他交互等,具体取决于具体检查的内容。

Details are commented in Snippet 详细信息在Snippet中进行了注释

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> 

There is very basic mistake in your markup you should not use elements with same id's in 您的标记中存在非常基本的错误,您不应该使用具有相同ID的元素

You can use class instead of id ( give class to radioboxes ) 您可以使用class而不是id( 将类赋予radioboxes

document.getElementsByClassName("userRoles") document.getElementsByClassName( “的UserRole”)

<input type="radio" class="userRoles" name="userRoles" value="1" onmousedown="checkUrole()">Admin

Rest of your code seems ok 其余的代码似乎没问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM