0

I'm trying to do this:

var linha = $(this).parent().parent()

$("#modal-footerMsg").append(
         "<button type='button' id='btnOK' 
                       class='btn btn-md' onclick='RemoveLinha(" + linha + ");'> OK");

which will execute this function:

function RemoveLinha(element) {
    element.parent().parent().remove();
}

how can i do this? Pass the jquery object to the function?

3
  • onclick='RemoveLinha(linha);'> ? it's just a string... Commented Nov 23, 2017 at 16:31
  • Just like any other object, give it to the function parameter. Maybe the flaw is in the logic that linha is someones parent parent then again you go for parent parent then delete it. Certanly don't pass the string linha .. Commented Nov 23, 2017 at 16:32
  • but when i do like i wrote, gives me an error.."Unexpected token }" Commented Nov 23, 2017 at 16:52

2 Answers 2

2

Hi attach event listener after appending your HTML like this

$(document).ready(function(){
var linha = $("#removeElm")
$("#modal-footerMsg").append("<button type='button' id='btnOK' class='btn btn-md'> OK</button>");

$("#btnOK").on("click",function(){
RemoveLinha(linha);
})

function RemoveLinha(element) {
    element.remove();
}
})
Sign up to request clarification or add additional context in comments.

Comments

1

Currently you are trying to put a jQuery object - literally an object, not a string representation of it - into a string. This won't work.

You are already using jQuery, which is great for constructing elements and creating event handlers on those elements, without reverting to setting inline strings of onclick="". Create the button element separately, setup the click event handler, then append it to the modal:

// get parent element
var linha = $(this).parent().parent();

// create a button
var button = $('<button type="button" id="btnOK" class="btn btn-md" />');

// add click event handler to button
button.click(function() { RemoveLinha(linha); });

// append button and text to modal
$("#modal-footerMsg").append(button, "OK");

Or if you want to be concise but messy:

var linha = $(this).parent().parent();

$("#modal-footerMsg").append(
    $('<button type="button" id="btnOK" class="btn btn-md" />')
        .click(function() { RemoveLinha(linha); }),
    "OK"
);

Comments

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.