3

I've got a strange question. We have buttons that have data attributes with an id in it. [v1, v2 and v3].

<table id="table-1" data-car-id="v1">
    <tr><td>Header1</td></tr>
    <tr><td>Content1 <input type="text" name="car[v1][marked][12]" /></td></tr>
    <tr><td>Footer</td></tr>
</table>

<button id="copy-2" data-car-id="v2">Copy Table</button>
<table id="table-2">

</table>

<button id="copy-3" data-car-id="v3">Copy Table</button>
<table id="table-3">

</table>

A little piece of Javascript copies the body of the above table to closest next one. (That works).

$("button[id^='copy']").click(function() {
    var $carId = $(this).attr('data-car-id');
    alert($carId);
    var $prevTable = $(this).prev("table[id^='table-']").prop('innerHTML');
    var $nextTable = $(this).next("table").html($prevTable);
});

But now the tricky part, the input name of all inputs in that tbody should be replace. While the market should remain unchanged

car[v1][marked][12] => car[v2][marked][12]

How can I do that? Make it yourself easy and use the JSFiddle I created: https://jsfiddle.net/ra35z8ff/

1 Answer 1

4

After copying the HTML over to the next table element, select all the children input elements and iterate over them. Use the .replace() method to replace the previous table element's data-car-id attribute with the current button element's data-car-id attribute.

Updated Example

$("button[id^='copy']").on('click', function () {
    var id = $(this).attr('data-car-id'),
        previousId = $(this).prev('button').attr('data-car-id');
        html = $(this).prev("table[id^='table-']").prop('innerHTML');

    $(this).next("table").html(html).find('input').each(function () {
        this.name = this.name.replace(previousId, id);
    });
});
Sign up to request clarification or add additional context in comments.

1 Comment

Josh thanks for your help. I've edited the answer as it was grabbing the id from the wrong element. Not table but the button carries the id

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.