skip to Main Content

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.

2

Answers


  1. You can call a JavaScript function from jQuery by using the eval() function. Here’s an example of how you can modify your code to call the checkDisplayOption function:

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

    This will evaluate the string stored in the data-display attribute of the #id001 element and execute it as JavaScript code. In this case, it will call the checkDisplayOption function with the specified parameters.

    Login or Signup to reply.
  2. 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">
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search