首页 > 解决方案 > How to capture choice from a list nested with a radio button

问题描述

I am loading an HTML page which dynamically populates the result of a search (for a book) in a set of lists attached to a radio button. The user is to choose which book in particular they are looking for from the set of lists by selecting the radio button and clicking "Submit".

How do I capture the ISBN from the list for the radio button that the user selects? Code below.

<form id="user_choice" action="/search" method="post">
      {% for data in data %}
          <div class="form-group">    
              <input type="radio" value="book_choice" id="choice" onClick="userSelection(document.getElementById('choice').value">
                  <ul>
                     <li> ISBN: {{ data[0] }} </li>
                     <li> Title: {{ data[1] }} </li>
                     <li> Author: {{ data[2] }} </li>
                     <li> Year: {{ data[3] }} </li>
                  </ul>
          </div>
          <br>    
      {% endfor %}
      <button class="btn btn-primary" onClick="submitUserSelection()">Select</button>
</form>

标签: javascripthtmlejs

解决方案


由于您已经在点击时获取了收音机的值,您可以将值属性更改为书籍 ISBN。前任:

<form id="user_choice" action="/search" method="post">
        {% for data in data %}
            <div class="form-group">    
                <input type="radio" value="{{ data[0] }}" onClick="userSelection(this.value)">
                    <ul>
                        <li>ISBN: {{ data[0] }}</li>
                        <li>Title: {{ data[1] }}</li>
                        <li>Author: {{ data[2] }}</li>
                        <li>Year: {{ data[3] }}</li>
                    </ul>
            </div>
            <br>    
        {% endfor %}
        <button class="btn btn-primary" onClick="submitUserSelection()">Select</button>
    </form>

我还删除了重复的 id,因为您永远不想拥有重复的 id


推荐阅读