I am dynamically creating a table which includes some dynamically generated buttons. I have done the same thing before using POST
and it worked. Now I'm using AJAX so I need to get the value of the hidden form
element via the click event. But, it always gives me the first value (first row/form).
Below is example of stripped down code.
Must I have a different name for each button? If so, how would I bind all those to a click event?
<pre><code>
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="assets/js/jquery.min.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function () {
$(document).on("click", "input[name='vsu']", function(event){
console.log('sliste'+$("input[name='sliste']").val());
event.preventDefault();
});
});
</script>
</head>
<body>
<table id="slist">
<tbody>
<tr>
<td>user1</td>
<td>
<form>
<input type="hidden" name="sliste" value="1">
<input name="vsu1" type="submit" value="view">
</form>
</td>
</tr>
<tr>
<td>user2</td>
<td>
<form>
<input type="hidden" name="sliste" value="2">
<input name="vsu2" type="submit" value="view">
</form>
</td>
</tr>
</tbody>
</table>
</body>
</html>
</pre></code>
You need to find the input element which is the previous sibling of the clicked button so
$(document).ready(function () {
$(document).on("click", "input[name='vsu']", function (event) {
console.log('sliste' + $(this).prev("input[name='sliste']").val());
event.preventDefault();
});
});
When you use $("input[name='sliste']")
as the selector it will find all the input elements with the given name then when you use .val()
as a getter it will return the value of the first element in the given set of elements.
$(document).ready(function() { $(document).on("click", "input[name='vsu']", function(event) { console.log('sliste' + $(this).prev("input[name='sliste']").val()); event.preventDefault(); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <table id="slist"> <tbody> <tr> <td>user1</td> <td> <form> <input type="hidden" name="sliste" value="1"> <!-- changed the button type since the code snippet does not allow submit requests--> <input name="vsu" type="button" value="view"> </form> </td> </tr> <tr> <td>user2</td> <td> <form> <input type="hidden" name="sliste" value="2"> <input name="vsu" type="button" value="view"> </form> </td> </tr> </tbody> </table>
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.