简体   繁体   中英

JavaScript - Setting value of element not working

I'm working on a code whose snippet I have attached below (JavaScript embedded in JSP), where rs is result set from an SQL query. I'm trying to assign a value to the edit button dynamically. But when I check the value of the button, its printing out to be null. I have also tried doing it using the setAttribute() method but the result was the same. What am I doing wrong?

...
while(rs.next()){
                <tr>
                    <td><%=rs.getInt(1) %></td>
                    <td><%=rs.getString(2) %></td>
                    <td id="edit"><button type="button" onclick="document.write(5 + 6)">Edit</button></td>
                    <td id="delete"><button type="button" onclick="document.write(5 + 6)">Delete</button></td>
                    <script>
                        var v = "edit".concat("<%=rs.getInt(1)%>");
                        document.getElementById("edit").value = v;
                    </script>
                </tr>
                } 
...

Unless you have a reason to do it via a script tag, you can achieve this by in-lining the value attribute just like you're doing with other rs values:

...
while(rs.next()){
    <tr>
        <td><%=rs.getInt(1) %></td>
        <td><%=rs.getString(2) %></td>
        <td><button type="button" onclick="document.write(5 + 6)" value="edit<%=rs.getInt(1)%>">Edit</button></td>
        <td id="delete"><button type="button" onclick="document.write(5 + 6)">Delete</button></td>
    </tr>
} 
...

If you want to do it with script, @Kaiido's comment should help you - move the id="edit" inside the <button> , but note that you want to also change it to id="edit<%=index%>" and add declaration and an increment of index in the server code. Or use another value as a differentiator, otherwise you'll end up with many id="edit" buttons and the script won't work as expected.

Try this by setting id property to edit button instead of td element.

     while(rs.next()){
                <tr>
                    <td><%=rs.getInt(1) %></td>
                    <td><%=rs.getString(2) %></td>
                    <td><button id="edit" type="button" onclick="document.write(5 + 6)">Edit</button></td>
                    <td><button id="delete" type="button" onclick="document.write(5 + 6)">Delete</button></td>
                    <script>
                        var v = "edit".concat("<%=rs.getInt(1)%>");
                        document.getElementById("edit").value = v;
                    </script>
                </tr>
                }

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