3

I dont know why the radiobutton wont set checked. I tried all the methods i could find but it won't work.

How I want it to work is that Type1 radiobutton is set checked if the value is 1; if the value is 0, Type2 radiobutton is set checked.

I printed the value in a textfield. The value is from a database btw. Nothing's wrong with getting the value from the database and printing it in the textfield.

My only problem is setting the radio buttons checked based on the value in the textfield.

I put an alert() in the function but it seems that it wont display an alert too. I think it doesn't call the function from the commmon.js. But other functions in common.js works though. :/

Here's the code;

common.js

var selected;

function SetRadiobuttonValue()
{
    selected = document.getElementById('myType').value;
    alert(selected);
    if(selected == "" || selected == 0){
        document.getElementById("type1").checked = true;
        document.getElementById("type2").checked = false;
    }else if(selected == 1){
        document.getElementById("type1").checked = false;
        document.getElementById("type2").checked = true;
    }
}

form.jsp

    <input type="text" id="myType" name="admin" value="${usersModule.adminFlag}" onChange=" SetRadiobuttonValue()">
    <label><input type="radio" name="type" id="type1" value="0" > General User</label>
    <label><input type="radio" name="type" id="type2" value="1" > Admin</label>

To those who tried to answer but still wont work:

I have another example: Imagine editing a profile form and there is the radio buttons of Male and Female. If it is Male in the profile info, the Male radio button is set checked or vice versa.

That's what i want to happen. But the radio button wont set checked. :(

UPDATE

I found the answer now. Thanks to @ketan :D I just have to put the function on body tag onLoad event to make it work. :D

Ruby
  • 241
  • 1
  • 6
  • 14

7 Answers7

1

maybe your script runs before DOM nodes are ready,try moving <script> SetRadiobuttonValue();</script> after your label and input tags

Roscoe
  • 19
  • 2
1

With JQuery

$('#myType').on('input', function() {
  var val = this.value;
  var rdo = $('input[name=type]:eq(0)');
  if (val)
    rdo = $('input[name=type][value=' + val + ']');
  rdo.prop('checked', true);
}).trigger('input');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" id="myType" name="admin" value="0">
<label>
  <input type="radio" name="type" id="type1" value="0">General User</label>
<label>
  <input type="radio" name="type" id="type2" value="1">Admin</label>
1
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>

<script>
    function SetRadiobuttonValue() {
        var selected;
        selected = document.getElementById('myType').value;

        if (selected == "1") {
            document.getElementById("type1").checked = true;
            document.getElementById("type2").checked = false;
        } else if (selected == "0") {
            document.getElementById("type1").checked = false;
            document.getElementById("type2").checked = true;
        }
    }

</script>
</head>
<body>

 <input type="text" id="myType" name="admin" value="" onChange=" SetRadiobuttonValue()">
    <label><input type="radio" name="type" id="type1" value="0" > General User</label>
    <label><input type="radio" name="type" id="type2" value="1" > Admin</label>

</body>
</html>
Jobelle
  • 2,717
  • 1
  • 15
  • 26
1

Your updated code : just one change see my comment

var selected;

    function SetRadiobuttonValue()
    {
        selected = document.getElementById('myType').value;

        if(selected == "" || selected == "0"){ // change here --- 0 to "0"
            document.getElementById("type1").checked = true;
            document.getElementById("type2").checked = false;
        }else if(selected == "1"){ // change here --- 1 to "1"
            document.getElementById("type1").checked = false;
            document.getElementById("type2").checked = true;
        }
    }

//More improved answer:

var selected;
function SetRadiobuttonValue(){
     selected = document.getElementById('myType').value;
     $('input:radio[name="type"]').filter("[value=" + selected + "]").prop("checked", "checked");
}

demo

Mahesh
  • 1,063
  • 1
  • 12
  • 29
1

Your'e only a couple of extra lines of code away, you were very close:

  • You had 2 conditionals if and else if, so you needed an else.

    • When you have 2 if-ish conditionals, then use if and else,
    • and if you have more than 2, then start with if continue using else if until the last conditional being else.
  • Made var selected into a number:

    • selected = parseInt(document.getElementById('admin').value, 10);
  • Added an eventListener on the text input.

  • Made the form a little fancy.

  • BTW, the demo below is functional as well. Enter a 0 and the first radio is checked, enter a 1 and the second radio is checked. The other condition "" (empty string?) is hard to replicate on a change or input event.

  • You can view the console output with developer tools.

Note: I changed #myType to #admin

<!doctype html>
<html>

<head>
  <meta charset="utf-8">
  <title>SO34984810</title>
</head>

<body>
  <form id="formSet" name="formSet" method="" action="">
    <fieldset>
      <legend>User Groups</legend>
      <input type="text" id="admin" name="admin" value="">
      <label>
        <input type="radio" name="type" id="type1" value="0">General User</label>
      <label>
        <input type="radio" name="type" id="type2" value="1">Admin</label>
    </fieldset>



    <script>
      function SetRadiobuttonValue(selected) {
        var out1 = document.getElementById('out1');
        selected = parseInt(document.getElementById('admin').value, 10);
        console.log('selected: ' + selected);
        if (selected === "" || selected === 0) {
          document.getElementById("type1").checked = true;
          document.getElementById("type2").checked = false;
          console.log('type1: ' + document.getElementById("type1").checked);
        } else if (selected === 1) {
          document.getElementById("type1").checked = false;
          document.getElementById("type2").checked = true;
          console.log('type2: ' + document.getElementById("type2").checked);
        } else {
          console.log(selected + ' is INVALID');
          return false;
        }
      }

      document.getElementById('admin').addEventListener('input', function(e) {
        var sel = this.value;
        SetRadiobuttonValue(sel);
      }, false);
    </script>
</body>

</html>
zer00ne
  • 41,936
  • 6
  • 41
  • 68
  • whats the e in function(e)? – Ruby Jan 25 '16 at 05:25
  • It is [`event`](https://developer.mozilla.org/en-US/docs/Web/API/Event) object like `event.target` or `event.preventDefault()` like any parameter in JS, it doesn't have to be used. I put it in there as a reflexive habit. You might also see it as `function(event) {` or `function(evt) {`as well. – zer00ne Jan 25 '16 at 05:28
  • this is not what i want. the textfied has already the value. I dont need to input a value to set the radio button. What i mean is that as document loads, it will check what value is in the textfield and set checked corresponding button . Imagine editing a profile form and there is the radio buttons of Male and Female. If it is Male in the profile info, the Male radio button is set checked or vice versa. – Ruby Jan 25 '16 at 05:34
  • Ok, that's easy so you just want the var selected to be entered on load? – zer00ne Jan 25 '16 at 05:37
  • yes and also when there is a change, the value is change in the textfield as well. All the answers here is only waiting for the change event in the textfield to set checked the radio button. Which doesnt solve my problem. :( – Ruby Jan 25 '16 at 05:40
  • My solution auto checks the radio according to the input of text, do you want me to put an eventListener on the radios and the value be reflected in the text box as well? – zer00ne Jan 25 '16 at 05:51
  • no need. i already found the answer. thanks for helping me though :) – Ruby Jan 25 '16 at 06:04
1

You can try in this way.

JS :

window.onload = function(){

            var selected;

            var myType = document.getElementById('myType');


            myType.addEventListener('change', function ()
            {
                selected = document.getElementById('myType').value;
                alert(selected);
                if(selected == "" || selected == 0){
                    document.getElementById("type1").checked = true;
                    document.getElementById("type2").checked = false;
                }else if(selected == 1){
                    document.getElementById("type1").checked = false;
                    document.getElementById("type2").checked = true;
                }
            }); 
        }   

HTML :

<input type="text" id="myType" name="admin" value="1">
<label><input type="radio" name="type" id="type1" value="0" > General User</label>
<label><input type="radio" name="type" id="type2" value="1" > Admin</label>

Here is the Plunker

RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53
0

please try this i run this code in all browser in this code onload javascript event i call ch() function in ch()function i set radio button is checked the javascript

<html>
<head>
 <title>check radio button</title>
 <script type="text/javascript">
  function ch()
  {
   document.getElementById("rd1").checked = true;
  }
 </script>
</head>
<body onload="ch();">
 <input type="radio" name="rd1" value="radio1" id="rd1">radio1
</body>
</html>
ketan
  • 12
  • 5