Search code examples
javascriptinputradio-buttonselector

How to select my second radio button in javascript without using id?


Hee, I'm working on something but can and dont want to change the HTML. Adding an ID button is not possible. I want to select the second radio input.

This is the html:

  <fieldset>
        <legend>I want to sign up:</legend>
        <label>
            <input type="radio" name="submit-for" value="project">
            <span>For project</span>
        </label>
        <label>
           <input type="radio" name="submit-for" value="stage">
           <span>As intern</span>
       </label>
  </fieldset>

This are the ways i tried selecting it in javascript but it didnt work:

   document.querySelector('input[type="radio"]:nth-of-type(2)').onclick = function () {
       document.getElementById("project").style.display = 'none';
       document.getElementById("stage").style.display = 'block';
   };

and

   document.querySelector('input[type="radio"]:nth-child(2)').onclick = function () {
       document.getElementById("project").style.display = 'none';
       document.getElementById("stage").style.display = 'block';
   };

Can someone please help?


Solution

  • Do you really want to select "the second" radio button, or do you want to select "the radio button with value 'stage'"? The second option sounds more extensible.

    document.querySelector('input[type="radio"][value="stage"]')
    

    EDIT: Also, upvoted your question for not resorting to ID usage. Always good practice, whether or not you're forced into it.