Home > Blockchain >  HTML dropdown select for generated list of users only passes value of first user
HTML dropdown select for generated list of users only passes value of first user

Time:08-06

I am creating a template that pulls in a list of users from the db, and each user row has a dropdown select to change their user type (this is an admin page). I'm trying to get the dropdowns to submit the change asynchronously. Right now, I'm only able to get dropdown select values from the first user. I'm trying to get the functionality to work for all the users listed on the page. Here's the (EJS and JS) code:

users.ejs

<table >
                <thead>
                    <tr>
                          ...
                    </tr>
                </thead>
                <tbody >
                    <% for (let user of users) { %>
                        <tr >
                            <th scope="row"><%= user.user_id %></th>
                            <td><%= user.username %></td>
                            <td><%= user.email %></td>
                            <td><%= user.user_type %></td>
                            <td>
                                <select name="user-types" id="user-type-select" >
                                    <option value="admin" >Admin</option>
                                    <option value="dealer" >Dealer</option>
                                    <option value="user" >User</option>
                                </select>
                                <input type="hidden" value="<%= user.user_id %>" name="userId" id="userId">
                                <button id="update-user-type"  type="button">Update User Type</button>
                            </td>
                            <td><%= user.is_active %></td>
                        </tr>
                    <% } %>

                </tbody>
            </table>

adminUsersScript.js

document.addEventListener("click", (e) => {
        if (e.target && e.target.classList.contains("button")) {
            const selectElement = document.getElementById("user-type-select")
            const selectElementValue = selectElement.options[selectElement.selectedIndex].value;
            const text = selectElement.options[selectElement.selectedIndex].text;
            //const selectUserId = document.getElementById("userId")
            //const userIdValue = selectUserId.value
            //console.log(userIdValue)
            console.log(selectElementValue)
            console.log(text)
        }

    })

CodePudding user response:

You need a unique id:

<select name="user-types" id="user-type-select-<%= user.user_id %>" >

And in JS, modify line 3 to select the element with an ID value starting with "user-type-select-":

document.addEventListener("click", (e) => {
        if (e.target && e.target.classList.contains("button")) {
            const selectElement = document.querySelectorAll('[id^="user-type-select-"]')[0]
         // ...

  • Related