简体   繁体   中英

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?

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.

document.querySelectorAll('fieldset input[type="radio"]')[1]=function () {
  document.getElementById("project").style.display = 'none';
         document.getElementById("stage").style.display = 'block';
    };

You can use document.getElementByName and select the second of the set:

document.getElementsByName("submit-for")[1];

The user @somethinghere was close and the OP chose an answer that did not apply to the title of the question so for those who are looking for the answer to the title of the question here you go:

var r = document.querySelectorAll('input[type="radio"]');
if (r.item.length > 0) {console.log(r.item(1));

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