-2

I do have a input type checkbox which has a data attribute on that. data attribute contains a javascript method which need to be executed on click of that textbox.

<input type="checkbox" id="id001" data-display="checkDisplayOption(p1,p2,p3);">

Now in jQuery -

$("#id001").click(function(){
     $("#id001").data("display");
});

I am looking for $("#id001").data("display"); to trigger checkDisplayOption method but it is not happening.

12
  • 3
    Calling a function in JS needs () at the end. Commented Apr 28, 2023 at 12:29
  • 3
    And the ID selector needs the # prefix. Commented Apr 28, 2023 at 12:31
  • 3
    Just to be clear, jQuery is JavaScript Commented Apr 28, 2023 at 12:32
  • Does this answer your question? How to call javascript function inside jQuery Commented Apr 28, 2023 at 12:33
  • 2
    You got no actual function here though, you got a string value that contains some code, but that code has not been parsed as JavaScript. You would actually need to eval this ... Commented Apr 28, 2023 at 12:33

1 Answer 1

0

The selector in the jQuery code is missing the # symbol to select the checkbox by its ID. It should be $("#id001").click(function(){...

A better approach would be to store the function name as the value of the data-display attribute.

Try below code

$("#id001").click(function () {
    var functionName = $(this).data("display");
    var params = $(this).data("params").split(",");
    window[functionName].apply(this, params);
});

function checkDisplayOption(p1, p2, p3) {
    console.log("checkDisplayOption called with params:", p1, p2, p3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="id001" data-display="checkDisplayOption" data-params="p1,p2,p3">

Sign up to request clarification or add additional context in comments.

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.