user1889849 user1889849 - 4 months ago 16
Javascript Question

Use JQuery to copy value from table to modal

I have a table with a list of all my data

<table>
<td>
<input type="hidden" value="<c:out value="${user.id}" />" name="userId" />
</td>
<td>
<button class="btn btn-default fileUpload" data-toggle="modal" id="btnUpload" data-target="#file-modal" value="<c:out value="${user.id}" />">Upload</button></td>
</table>


and i have a modal container. When the upload button in the table is clicked, the modal will open up for a file upload.

<form action="${pageContext.request.contextPath}/UserServlet" enctype="multipart/form-data" method="post">
<input type="hidden" value="5519" name="OPS" />
<input type="hidden" name="uploadUserId" />
<div class="form-group">
File : <input type="file" class="file" name="uploadFile"><br />
<button type="submit" class="btn btn-default">Upload</button>
<br /><br />
</div>
</form>


What i am trying to do is on the click of btnUpload the value in the hidden input type userId will be copied over to the hidden value type uploadUserId

I have tried doing the following but neither works

1



$(document).ready(function () {
$("#btnUpload").click(function(){
var $userId = $(this).closest("tr").find("#userId").text();
$("#uploadUserId").val($userId);
});
});


2



$(document).ready(function () {
$("#btnUpload").click(function(){
var $userId = $(this).closest("tr").children()[2].text();
$("#uploadUserId").val($userId);
});
});

Answer

This will do the trick without changing the html

$(document).ready(function () {
    $("#btnUpload").click(function(){
        var $userId = $(this).parent().prev("td").children("input:hidden").val();
        $("#uploadUserId").val($userId);
    }); 
});

Another solution by adding ID to the input element as shown below,

  <input id="userVal" type="hidden" value="<c:out value="${user.id}" />"name="userId" /> 

then you can get the value from the following jquery

   $("#userVal").val();