0

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

Mohammad
  • 21,175
  • 15
  • 55
  • 84
MikeBroski
  • 64
  • 1
  • 8
  • I don't understand what you want exactly. Do you want to add input to all `tr` when one button is clicked? – Mohammad Jun 05 '16 at 10:30
  • I want the contents of the row that I contains button into a readonly input – MikeBroski Jun 05 '16 at 10:58
  • `this` is element event occurred on in any jQuery event handler. Use traverses up to row like `closest()` then `find()` within row. Note that you are duplicating ID's and id must be unique in page by definition. Not really clear what expected results are or where the readonly elements are – charlietfl Jun 05 '16 at 11:04
  • How does the closest to work? I heard of this never tested it in parctice could you give an example? – MikeBroski Jun 05 '16 at 13:05

1 Answers1

1

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>
Mohammad
  • 21,175
  • 15
  • 55
  • 84