myRM
myRM

Reputation: 249

jQuery to Javascript conversion

Updated:

I have a JavaScript function inserted in a button. Just want to convert some of its jQuery codes to pure js coz I can't access codes with $(this).

My Code:

function editcheck(el) {
    $(el).parent().parent().remove();
    var tableData = $(el).closest('#paytable tr').children("td").map(function () {
    return $(el).text();
}).get();

$('#checkamount').val($.trim(tableData[1]));
}

code/function before calling the editcheck:

var table = document.getElementById('paytable');
table.innerHTML += '<tr id="checktitle" style="border: none;"><td width="137px"><label>CHECK</label></td>' +
                    '<td class="rowAdd" width="125px">' + checkamounts.join("") + '</td>' +
                    '<td width="127px">' + checknos.join("") + '</td>' +
                    '<td style="display: none">' + dbank.join("") + '</td>' +
                    '<td style="display: none">' + draweedesc.join("") + '</td>' +
                    '<td style="display: none">' + pickercheck.join("") + '</td>' +
                    '<td><button title="Edit" onclick="editcheck(this)" type="button" style="width: 30px; height: 18px"><img src="images/editimg.png" width="13" height="13"></button></td>';

P.S I can't use $("#elementid").click(function() because the line will exist after appending it.

Upvotes: 2

Views: 111

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388416

When you invoke editcheck in the inline handler this inside it refers to the window object

You can pass a custom execution context using .call() like editcheck.call(this)

<button title="Edit" onclick="editcheck.call(this)" style="width: 30px; height: 18px">

or pass the clicked element reference as a argument like

<button title="Edit" onclick="editcheck(this)" style="width: 30px; height: 18px">

then

function editcheck(el) {
    var $tr = $(el).closest('tr');
    var tableData = $tr.children("td").map(function () {
        return $(this).text();
    }).get();
    $tr.remove();
    $('#checkamount').val($.trim(tableData[1]));
}

Solution Use Event Delegation

<button title="Edit" class="edit" type="button" style="width: 30px; height: 18px"><img src="images/editimg.png" width="13" height="13"></button>

then

jQuery(function () {
    $('#Paytable').on('click', '.edit', function () {
        var $tr = $(this).closest('tr').remove();
        $('#checkamount').val($.trim($tr.find('td:first').text());
    });
})

Upvotes: 1

Related Questions