简体   繁体   中英

Grab the values of a select tag inside a foreach loop

So what I have is aa for each loop in jsp file (or html) that is iterating over a set of data which is an array and in that loop I have a select tag that selects an option. This is suppose to display a row and each row has a select option. What I want to do is grab each instances of the value of the select tag. I tried doing this with JQuery with many different types of identifiers but no matter how i try to experiment it either returns nothing, undefined or the very first instance of the select tag but not the followings. Can anyone help me?

<c:forEach var="temp" items="${data}" id="loop">

    <tr><td>
    <div class="dropdown">
        <select class="btn btn-secondary dropdown-toggle select" name="${temp.id}" >
            <option value="1" class="dropdown-item btn btn-secondary dropdown-toggle" > Pending </option>
            <option value="2" class="dropdown-item btn btn-secondary dropdown-toggle" > Approve </option>
            <option value="3" class="dropdown-item btn btn-secondary dropdown-toggle" > Deny </option>
        </select>
     </div>
     </td></tr>
</c:forEach>
/*****************************************************
                 JQuery Code
*****************************************************/
 $("#update").click(function() {
      var index = $("select.statues").val();
      console.log(index);
    /* $.each(index, function(i, item){
        console.log(item);
  });*/
});

The update id is an input tag that comes after all the html stuff

$("select.statues").val(); get you the current selected option.

You will have to fetch all the selects first and iterate over them to get the corresponding value.

You are looking for

$("#update").click(function() {
   var $selects = $(".select");
   console.log($selects);
   $.each($selects, function(i, item) {
     // selected value
     var $currSelect = $(item)
     console.log($currSelect.val());
     // Selected option text
     console.log($currSelect.find('option:selected').text());
   });
 });

Check Fiddle

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