简体   繁体   中英

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.

To send data I'm using a JavaScript(Ajax) which is bound to a button click event.

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

 <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,

<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.

So is there any way I solve this and I like to use JavaScript if can.

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.

My 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:

$(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.

Firstly, you don't need the id 's on every input element. 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:

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

JsFiddle Example

UPDATE - improved

A more efficient method would be using the Array.prototype.find() method, this is better because:

The find method executes the callback function once for each index of the array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element.

In other words, it doesn't need to iterate the entire Array , once we find what we want it returns.

Note: Use the below snippets within the change event mentioned above to retrieve the checked value.

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

JS (Without 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

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

 // 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

You can use class instead of id ( give class to radioboxes )

document.getElementsByClassName("userRoles")

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

Rest of your code seems ok

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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