MikeBroski MikeBroski - 6 months ago 10
Javascript Question

Getting tables div content when pressed button into input

I want to get contents of each rows and write it in input but i can't do this work.

<table>
<tbody>
<tr>
<td>
<div id="a">abc</div>
</td>
</tr>
<tr>
<td>
<div id="b">abcd</div>
</td>
</tr>
<tr>
<td>
<div id="c">abcdf</div>
</td>
</tr>
<tr>
<td>
<div id="d">abcde</div>
</td>
</tr>
<tr>
<td>
<button class="magicButton">choose this row</button>
</td>
</tr>
</tbody>
</table>


$(document).ready(function(){
$('.magicButton').click(function(){
// insert text of div a into input
// insert text of div b into input
// ect
});
});


Once you press the button it gets this values into following

<input type="text" name="whatver" div="fromValueA" readonly>
<input type="text" name="whatver" div="fromValueB" readonly>
<input type="text" name="whatver" div="fromValueC" readonly>
<input type="text" name="whatver" div="fromValueD" readonly>


How exactly can I get this to not just use the same A, B ,C from all buttons that are made

Best wishes, Mike

Answer

Use jquery replaceWith() method to replacing div with input.

$("button").click(function(){
    $("table td > div").replaceWith(function(index, text){
        var id = "fromValue" + $(this).attr("id");
        return "<input id='" + id + "' value='" + text + "' />";
    });
});
table, tr, td {
    border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr>
        <td>
            <div id="a">A</div>
        </td>
     </tr> 
     <tr>
        <td>
            <div id="b">B</div>
        </td>
     </tr> 
     <tr>
        <td>
            <div id="c">C</div>
        </td>
     </tr> 
     <tr>
        <td>
            <button>Change</button>
        </td>
     </tr> 
</table>