Home > Software engineering >  How to get the value of a selected radio input element with javascript
How to get the value of a selected radio input element with javascript

Time:07-18

  <input type="radio" name="programming" id="" value="HTML">HTML</input>
  <input type="radio" name="programming" id="" value="C  ">C   </input>
  <input type="radio" name="programming" id="" value="JavaScript">JavaScript </input>
  <input type="radio" name="programming" id="" value="Python">Python</input>
  <button type="submit" >check</button>

Here is my html code I'm trying to get the value of the selected radio element after the click of the button element.

CodePudding user response:

// Selecting all the input with name of programming

const selectedRadio = document.querySelectorAll("input[name='programming']");

// selecting the btn to which we will add the event listener

const btn = document.querySelector(".submit");

// adding a click event to the selected button

btn.addEventListener('click', (e) => {
// looping through each btn and logging the value unto the console if it is checked
selectedRadio.forEach((element => {
    if(element.checked) {
        console.log(element.value);
    };
}));

});

CodePudding user response:

You can get the value with JavaScript with :

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

CodePudding user response:

<input type="radio" name="programming" id="" value="HTML">HTML</input>
<input type="radio" name="programming" id="" value="C  ">C   </input>
<input type="radio" name="programming" id="" value="JavaScript">JavaScript </input>
<input type="radio" name="programming" id="" value="Python">Python</input>
<button type="submit" id="submitBtn" >check</button>

<script>
    document.getElementById('submitBtn').onclick = function(){
       let val = document.querySelector('input[name="programming"]:checked').value; 
       console.log('Choosen: ', val)
    }
</script>

CodePudding user response:

Try this code :

const btnSubmit = document.querySelectorAll('input[type="submit"]');

btnSubmit.addEventListener('click', e => {
    let checkedInputValue = document.querySelectorAll('input[name="programming"]:checked').value;
    console.log(checkedInputValue);

});
  • Related