doucai6663 2019-05-29 19:02
浏览 55
已采纳

从填充列表中获取选定的选项ID

I have a radiobutton list that is populated from MySQL. A function to be called when the selected radiobutton changes. I would like to be get the ID of the selected item.

 <ul id="radio" class="input-list">
<?php
$stmt = mysqli_prepare($link, "SELECT id, name, price FROM cases ORDER BY price");
$stmt->execute();
$stmt->bind_result($case_id, $case_name, $case_price);
while($stmt->fetch()) {
echo '<li>
<input class="selectedoptions" id="'.$case_id.'" name="config-case" value="'.$case_price.'" type="radio" onchange="updateImage(this.id);">
<label class="sub-label" for="'.$case_id.'">'.$case_name.'         [£'.$case_price.']</label>
</li>';
}
$stmt->close();
>
</ul>

JS:

<script>

    function updateImage(caseid) {

        var selectmenuID = document.getElementById(caseid);
        console.log(selectmenuID);
    }

<script>

Attempting to get the id of the selected item is not successful. This is the console output:

<input class="selectedoptions" id="32" name="config-case" value="24"
type="radio" onchange="updateImage(this.id);">

I would like to get the 32 (the id). How can I do this? Thank you,

  • 写回答

2条回答 默认 最新

  • drn34916 2019-05-29 19:08
    关注

    Your code is right. The only fact about it is that you are logging in console the DOM element, not the parameter you recive caseid which value is the ID attribute of the element.

    Look at an example:

    function updateImage(caseid) {
      var selectmenuID = document.getElementById(caseid);
      console.log(`Clicked on radio input with id:${caseid}`);
    }
    <ul id="radio" class="input-list">
    
      <li>
        <input class="selectedoptions" id="1" name="config-case" value="'.$case_price.'" type="radio" onchange="updateImage(this.id);">
        <label class="sub-label" for="'.$case_id.'">Element with ID 1</label>
      </li>
      
      <li>
        <input class="selectedoptions" id="2" name="config-case" value="'.$case_price.'" type="radio" onchange="updateImage(this.id);">
        <label class="sub-label" for="'.$case_id.'">Element with ID 2</label>
      </li>
      
      <li>
        <input class="selectedoptions" id="3" name="config-case" value="'.$case_price.'" type="radio" onchange="updateImage(this.id);">
        <label class="sub-label" for="'.$case_id.'">Element with ID 3</label>
      </li>
    
    </ul>
    
    <input class="selectedoptions" id="32" name="config-case" value="24"
    type="radio" onchange="updateImage(this.id);">

    </div>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?