skip to Main Content

I have a list as shown below.
Now I want to get the values of each radio button when clicking on it. However, I get always the first value since the IDs (list-name) will be the same when rendered out the list.

Is there a simple way to do so? Maybe with onclick=function(this)

<form id="form-1">
{% for u in user %}
  <li>
    <div>
       <input id="list-name" type="radio" value="{{ u.name }}" name="list-radio">
       <label for="list-name">{{ u }}, {{ u.name }}</label>
    </div>
  </li>
{% endfor %}
</form>



<script>
    $(document).on('change', '#form-1', function (e){
      console.log($('#list-name').val())
    }
</script>

2

Answers


  1. The attribute id is unique in a document. Use class instead. Also use this keyword to refer the currently clicked element.

    Updated Code:

    <form id="form-1">
      {% for u in user %}
        <li>
          <div>
             <input class="list-name" type="radio" value="{{ u.name }}" name="list-radio">
             <label for="list-{{ u.name }}">{{ u }}, {{ u.name }}</label>
          </div>
        </li>
      {% endfor %}
    </form>
    
    <script>
        $(document).on('change', '.list-name', function (e){
          console.log($(this).val());
        });
    </script>
    

    Demo:

    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    
    <form id="form-1">
      <li>
        <div>
           <input class="list-name" type="radio" value="John" name="list-radio" id="list-John">
           <label for="list-John">User 1, John</label>
        </div>
      </li>
      <li>
        <div>
           <input class="list-name" type="radio" value="Jane" name="list-radio" id="list-Jane">
           <label for="list-Jane">User 2, Jane</label>
        </div>
      </li>
      
    </form>
    
    <script>
        $(document).on('change', '.list-name', function (e){
          console.log($(this).val());
        });
    </script>
    Login or Signup to reply.
  2. Now that these are radio buttons that at grouped by their name you can get the current value of the radioNodeList by its name on the form (form.list_radio.value).

    Don’t use hyphens in id or name values. If you feel like it, use underscore instead.

    document.forms.form_1.addEventListener('change', e => {
      let form = e.target.form;
      console.log(form.list_radio.value);
    });
    <form id="form_1">
      <ul>
        <li>
          <label><input type="radio" value="1" name="list_radio">Item 1</label>
        </li>
        <li>
          <label><input type="radio" value="2" name="list_radio">Item 2</label>
        </li>
      </ul>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search