skip to Main Content

I have three radio buttons in a group thus:

          <div class="form-check ml-4">
            <input class="form-check-input" type="radio" name="1" id="1" value="First">
            <label class="form-check-label" for="1">First</label>
          </div>
          <div class="form-check ml-4">
            <input class="form-check-input" type="radio" name="1" id="2" value="Second">
            <label class="form-check-label" for="2">Second</label>
          </div>
          <div class="form-check ml-4">
            <input class="form-check-input" type="radio" name="1" id="3" value="Third">
            <label class="form-check-label" for="3">Third</label>
          </div>

Using jQuery, how would I retrieve the nth-child number of a checked radio button in the group?

I tried this:

(($(find("input[type=radio]:checked")).attr('nth-child()')))

2

Answers


  1. You need to get the position of the div that wraps around the radio button, not the button itself.

    nth-child is not an attribute of an element. The .index() method will return the position of an element among its siblings.

    $(":radio:checked").closest("div.form-check").index()
    
    Login or Signup to reply.
  2. Maybe a bit late, but you didn’t explain the purpose of getting the nth child. My guess is that you would like to the the value of the selected radio button.

    With the name of the radio button group you can just ask for form.n1.value there n1 is the name.

    Note that the value for an id attribute should start with a letter (the id attribute).

    document.forms.form01.addEventListener('change', e => {
      let form = e.target.form;
      console.log(form.n1.value);
    });
    <form name="form01">
      <div class="form-check ml-4">
        <input class="form-check-input" type="radio" name="n1" id="id1" value="First">
        <label class="form-check-label" for="id1">First</label>
      </div>
      <div class="form-check ml-4">
        <input class="form-check-input" type="radio" name="n1" id="id2" value="Second">
        <label class="form-check-label" for="id2">Second</label>
      </div>
      <div class="form-check ml-4">
        <input class="form-check-input" type="radio" name="n1" id="id3" value="Third">
        <label class="form-check-label" for="id3">Third</label>
      </div>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search