Get the Value of Radiobutton Using JS
Asked Answered
K

3

7

Problem: I have not been able to get the value of a radiobutton or value in a textbox.

From trial and error, I found that the following gives me access to the information in div gender1

I could not figure out how to get the value of gender or age. I tried appending .value/.value(), using the id attribute, etc. I also tried various methods from a related question on stack overflow (Get Radio Button Value with Javascript), but had little success.

var checkedRadio = document.querySelectorAll('.w3-container')[0]
                        .querySelectorAll('#box')[0]
                     .querySelector('#gender1');

console.log( checkedRadio );
<body>
  <div class="w3-container">
    <div id="box" style="width:600px;height:650px;padding:10px;border:2px solid black;">
      <h5><b>Age (years):</b></h5>
      <div id="age">
        <input type="number" name="age1">
        <br>
      </div>
      <div id="gender1">
        <h5><b>Male or Female?</b>:
                    <input type="radio" id="r1" name="gender" value="Male"> Male
                    <input type="radio" id="r2" name="gender" value="Female"> Female
                </h5>
      </div>
    </div>
  </div>
</body>
Kileykilgore answered 29/1, 2017 at 9:11 Comment(0)
B
10

you can use

document.querySelector('input[name="gender"]:checked').value

to get the value.

document.getElementById("btn_click").addEventListener("click", function(){

  
  if(document.querySelector('input[name="age1"]').value !== "" && document.querySelector('input[name="gender"]:checked') !== null )
  {
  console.log("Age : ", document.querySelector('input[name="age1"]').value);
  console.log("Gender : ", document.querySelector('input[name="gender"]:checked').value);
   }
  else
  {
    console.log("Please provide all the details.")
   }
});
<body>
  <div class="w3-container">
    <div id="box" style="width:600px;height:650px;padding:10px;border:2px solid black;">
      <h5><b>Age (years):</b></h5>
      <div id="age">
        <input type="number" name="age1">
        <br>
      </div>
      <div id="gender1">
        <h5><b>Male or Female?</b>:
                    <input type="radio" id="r1" name="gender" value="Male" > Male
                    <input type="radio" id="r2" name="gender" value="Female"> Female
                </h5>
      </div>
      <input type="button" id="btn_click" value="Click">
    </div>
  </div>
</body>
Bowfin answered 29/1, 2017 at 9:17 Comment(7)
Thanks Deep! In testing this answer, however, it seems this requires one of the radio-buttons to be selected, otherwise it will return null. Am I correct in stating this?Kileykilgore
@Kileykilgore does it matter? because when the page loads, the radio buttons will not be selected... Note that Deep has a checked attribute in #r2...Jermainejerman
@Kileykilgore i have just modified the snippet to let user select values first and then print the list. Since the earlier snippet was printing the values on page load , i put a checked attribute iin the html itself as kukkuz explained.Bowfin
Thanks Deep! Really appreciate it. One last thing, how would you suggest error checking/avoiding the type error if the user presses click with no data entered.Kileykilgore
@Kileykilgore updated the snippet for a simple validation to check if user has provided both Age and Gender values.Bowfin
It there any browser compatibility table for this solution? Is it cross-browser?Rebbecarebbecca
Since this is a vanilla JavaScript solution , it will work with all modern browsers.Bowfin
J
2

You can use querySelector to select the textbox value or the value of the checked radio button like this:

var age = document.querySelector('input[type=number][name=age1]').value;
var gender = document.querySelector('input[type=radio]:checked').value;

See demo below:

function submit() {

  var age = document.querySelector('input[type=number][name=age1]').value;
  var gender = document.querySelector('input[type=radio]:checked').value;

  console.log(age, gender);

}
<div class="w3-container">
  <div id="box" style="width:600px;height:650px;padding:10px;border:2px solid black;">
    <h5><b>Age (years):</b></h5>
    <div id="age">
      <input type="number" name="age1">
      <br>
    </div>
    <div id="gender1">
      <h5><b>Male or Female?</b>:
                    <input type="radio" id="r1" name="gender" value="Male"> Male
                    <input type="radio" id="r2" name="gender" value="Female"> Female
                </h5>
    </div>
  </div>
</div>

<button onclick="submit()">Click me</button>
Jermainejerman answered 29/1, 2017 at 9:17 Comment(5)
What happens if he has more than one radio selection in same page?Rubyeruch
Ataur Rahman Munna, I think then you can just use a "name" argument instead of type in order to get the radio-button values.Kileykilgore
kukkuz, thanks for your comment. Do you have any suggestions on how to address cases where the user presses Click me without providing the inputs?Kileykilgore
Then you can update your answer as the answer is more specific.Rubyeruch
@Kileykilgore you can add some validation... Deep has added that to his answer I guess...Jermainejerman
A
2

You can use javascript onclick event. Please look in to the below example,

<script>
function getGender(gender) {
  alert(gender);
}
</script>    
<body>
        <div class="w3-container">
            <div id="box" style="width:600px;height:650px;padding:10px;border:2px solid black;">
                <h5><b>Age (years):</b></h5>
                <div id="age"><input type="number" name="age1"><br></div>
                <div id="gender1">
                    <h5><b>Male or Female?</b>:
                        <input type="radio" id="r1" name="gender" onclick = "getGender(this.value)" value="Male"> Male
                        <input type="radio" id="r2" name="gender" onclick = "getGender(this.value)" value="Female"> Female
                    </h5>
                </div>
            </div>
        </div>
        </body>

OR

<script>
function getValues() {
  // Get value of selected radio button
  var genderVal;
  if (document.getElementById('r1').checked) {
    genderVal = document.getElementById('r1').value;
  } else if (document.getElementById('r2').checked) {
    genderVal = document.getElementById('r2').value;
  }

  alert("Value of textbox:"+ document.getElementsByName("age1")[0].value+" Value of radio button:"+ genderVal);
}
</script>

<body>
  <div class="w3-container">
    <div id="box" style="width:600px;height:650px;padding:10px;border:2px solid black;">
          <h5><b>Age (years):</b></h5>
          <div id="age"><input type="number" name="age1"><br></div>
          <div id="gender1">
            <h5><b>Male or Female?</b>:
              <input type="radio" id="r1" name="gender" onclick = "getGender(this.value)" value="Male"> Male
              <input type="radio" id="r2" name="gender" onclick = "getGender(this.value)" value="Female"> Female
            </h5>
          </div>
          <div>
            <input type="button" value="GetValues" onclick="getValues()">
          </div>
        </div>
      </div>
</body>

Hope the above examples are helpful to you.

Adenovirus answered 29/1, 2017 at 9:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.