S.P.
S.P.

Reputation: 369

jQuery replace and add new string when click

I have a small form that has number and name on it. It shows number_name when you click button. For example, if you click button, it will popup 1,2_Tod, my question is... how to replace comma to underline between the number, so the number part will looks like 1_2 instead of 1,2, and add _ordered after the name part, so the name part will looks like Tod_ordered, and the whole string will looks like 1_2_Tod_ordered. And I have another question, is it possible to swap string when click button to make 1_2_Tod_ordered looks like Tod_ordered_1_2?

$('.button').click(function(){
    var data = $('.number,.name').map(function () {
		return $(this).text();
	}).get().join('_');
	
    alert(data);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<table id="dataTable">
    <tr id="data1">
        <td class="number">1,2</td>
        <td class="name">Tod</td>
    </tr>
     <tr id="data2">
        <td class="number">8,10</td>
        <td class="name">Smith</td>
    </tr>
</table>
<button type="button" class="button">Order</button>

JSFiddle

Upvotes: 0

Views: 74

Answers (1)

Raul
Raul

Reputation: 961

For getting data like: 1_2_Tod_ordered_8_10_Smith_ordered

Check this fiddle

$('.button').click(function(){
    var data1 = $('.number,.name').map(function () {
        var text = $(this).text();
        if($(this).hasClass('name')) {
            text += '_ordered';
        } else if($(this).hasClass('number')) {
            text = text.replace(/,/g, "_");
        }
        return text;
    }).get().join('_');

    alert(data1);
    console.log(data1);
});

<table id="dataTable">
    <tr id="data1">
        <td class="number">1,2</td>
        <td class="name">Tod</td>
    </tr>
     <tr id="data2">
        <td class="number">8,10</td>
        <td class="name">Smith</td>
    </tr>
</table>
<button type="button" class="button">Order</button>

Update

This has both the options:

1_2_Tod_ordered_8_10_Smith_ordered

Tod_ordered_1_2_Smith_ordered_8_10

Check this fiddle

Upvotes: 2

Related Questions