passing arguments in onclick functions appended from Javascript












3















I have a piece of code which looks like the following,






$(document).ready(function(){
var agr1='#19865 - testArg';
var arg2=1856
$('#dv_Test').append('<button onclick="testFunction('+ agr1 +','+ arg2 +')">Test</button>')
});
function testFunction(arg1, arg2) {
alert(arg1);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dv_Test"></div>





here I am getting error like the following



testFunction(#19865 - testArg,1856)  



Uncaught SyntaxError: Invalid or unexpected token




and my string agr1 doesn't have "" with itself



how can I solve this issue?










share|improve this question























  • But why are you using inline handlers? $('<button />').click(function() { // access scope variables normally})

    – Yury Tarabanko
    Jan 2 at 12:02











  • this is just an example I am getting data from database and binding this to table

    – user6656728
    Jan 2 at 12:03











  • your inline arguments should be strings if they are meant to be so. In a nutshell, you need to escape them, hence the "invalid or unexpected token" exception.

    – briosheje
    Jan 2 at 12:03








  • 2





    @MumbaiWadala " I am getting data from database and binding this to table" it doesn't really matter if you have access to the data (and I assume you do :)) You don't need inline handlers in year 2019.

    – Yury Tarabanko
    Jan 2 at 12:05
















3















I have a piece of code which looks like the following,






$(document).ready(function(){
var agr1='#19865 - testArg';
var arg2=1856
$('#dv_Test').append('<button onclick="testFunction('+ agr1 +','+ arg2 +')">Test</button>')
});
function testFunction(arg1, arg2) {
alert(arg1);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dv_Test"></div>





here I am getting error like the following



testFunction(#19865 - testArg,1856)  



Uncaught SyntaxError: Invalid or unexpected token




and my string agr1 doesn't have "" with itself



how can I solve this issue?










share|improve this question























  • But why are you using inline handlers? $('<button />').click(function() { // access scope variables normally})

    – Yury Tarabanko
    Jan 2 at 12:02











  • this is just an example I am getting data from database and binding this to table

    – user6656728
    Jan 2 at 12:03











  • your inline arguments should be strings if they are meant to be so. In a nutshell, you need to escape them, hence the "invalid or unexpected token" exception.

    – briosheje
    Jan 2 at 12:03








  • 2





    @MumbaiWadala " I am getting data from database and binding this to table" it doesn't really matter if you have access to the data (and I assume you do :)) You don't need inline handlers in year 2019.

    – Yury Tarabanko
    Jan 2 at 12:05














3












3








3








I have a piece of code which looks like the following,






$(document).ready(function(){
var agr1='#19865 - testArg';
var arg2=1856
$('#dv_Test').append('<button onclick="testFunction('+ agr1 +','+ arg2 +')">Test</button>')
});
function testFunction(arg1, arg2) {
alert(arg1);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dv_Test"></div>





here I am getting error like the following



testFunction(#19865 - testArg,1856)  



Uncaught SyntaxError: Invalid or unexpected token




and my string agr1 doesn't have "" with itself



how can I solve this issue?










share|improve this question














I have a piece of code which looks like the following,






$(document).ready(function(){
var agr1='#19865 - testArg';
var arg2=1856
$('#dv_Test').append('<button onclick="testFunction('+ agr1 +','+ arg2 +')">Test</button>')
});
function testFunction(arg1, arg2) {
alert(arg1);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dv_Test"></div>





here I am getting error like the following



testFunction(#19865 - testArg,1856)  



Uncaught SyntaxError: Invalid or unexpected token




and my string agr1 doesn't have "" with itself



how can I solve this issue?






$(document).ready(function(){
var agr1='#19865 - testArg';
var arg2=1856
$('#dv_Test').append('<button onclick="testFunction('+ agr1 +','+ arg2 +')">Test</button>')
});
function testFunction(arg1, arg2) {
alert(arg1);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dv_Test"></div>





$(document).ready(function(){
var agr1='#19865 - testArg';
var arg2=1856
$('#dv_Test').append('<button onclick="testFunction('+ agr1 +','+ arg2 +')">Test</button>')
});
function testFunction(arg1, arg2) {
alert(arg1);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dv_Test"></div>






javascript jquery






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 2 at 11:59







user6656728




















  • But why are you using inline handlers? $('<button />').click(function() { // access scope variables normally})

    – Yury Tarabanko
    Jan 2 at 12:02











  • this is just an example I am getting data from database and binding this to table

    – user6656728
    Jan 2 at 12:03











  • your inline arguments should be strings if they are meant to be so. In a nutshell, you need to escape them, hence the "invalid or unexpected token" exception.

    – briosheje
    Jan 2 at 12:03








  • 2





    @MumbaiWadala " I am getting data from database and binding this to table" it doesn't really matter if you have access to the data (and I assume you do :)) You don't need inline handlers in year 2019.

    – Yury Tarabanko
    Jan 2 at 12:05



















  • But why are you using inline handlers? $('<button />').click(function() { // access scope variables normally})

    – Yury Tarabanko
    Jan 2 at 12:02











  • this is just an example I am getting data from database and binding this to table

    – user6656728
    Jan 2 at 12:03











  • your inline arguments should be strings if they are meant to be so. In a nutshell, you need to escape them, hence the "invalid or unexpected token" exception.

    – briosheje
    Jan 2 at 12:03








  • 2





    @MumbaiWadala " I am getting data from database and binding this to table" it doesn't really matter if you have access to the data (and I assume you do :)) You don't need inline handlers in year 2019.

    – Yury Tarabanko
    Jan 2 at 12:05

















But why are you using inline handlers? $('<button />').click(function() { // access scope variables normally})

– Yury Tarabanko
Jan 2 at 12:02





But why are you using inline handlers? $('<button />').click(function() { // access scope variables normally})

– Yury Tarabanko
Jan 2 at 12:02













this is just an example I am getting data from database and binding this to table

– user6656728
Jan 2 at 12:03





this is just an example I am getting data from database and binding this to table

– user6656728
Jan 2 at 12:03













your inline arguments should be strings if they are meant to be so. In a nutshell, you need to escape them, hence the "invalid or unexpected token" exception.

– briosheje
Jan 2 at 12:03







your inline arguments should be strings if they are meant to be so. In a nutshell, you need to escape them, hence the "invalid or unexpected token" exception.

– briosheje
Jan 2 at 12:03






2




2





@MumbaiWadala " I am getting data from database and binding this to table" it doesn't really matter if you have access to the data (and I assume you do :)) You don't need inline handlers in year 2019.

– Yury Tarabanko
Jan 2 at 12:05





@MumbaiWadala " I am getting data from database and binding this to table" it doesn't really matter if you have access to the data (and I assume you do :)) You don't need inline handlers in year 2019.

– Yury Tarabanko
Jan 2 at 12:05












2 Answers
2






active

oldest

votes


















5














The issue is because the arg1 value is a string and needs to have quotes around it:






$(document).ready(function() {
var agr1 = '#19865 - testArg';
var arg2 = 1856
$('#dv_Test').append('<button onclick="testFunction('' + agr1 + '',' + arg2 + ')">Test</button>')
});

function testFunction(arg1, arg2) {
alert(arg1);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dv_Test"></div>





However a much better way to do this would be to put those values in data attributes and add a single delegated event handler to handle all dynamically created buttons. Try this:






$(document).ready(function() {
var agr1 = '#19865 - testArg';
var arg2 = 1856
var $div = $('#dv_Test').append('<button data-arg1="' + agr1 + '" data-arg2="' + arg2 + '">Test</button>');

$div.on('click', 'button', function() {
var $btn = $(this);
console.log($btn.data('arg1'), $btn.data('arg2'));
});
});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dv_Test"></div>








share|improve this answer
























  • thanks the second solution is really good and I will implement that.

    – user6656728
    Jan 2 at 12:08











  • No problem, glad to help

    – Rory McCrossan
    Jan 2 at 13:12



















1














You need to have quotes around the argument.Alternatively you can try template literals






$(document).ready(function() {
var agr1 = '#19865 - testArg';
var arg2 = 1856
$('#dv_Test').append(`<button onclick="testFunction('${agr1}','${arg2}' )">Test</button>`)
});

function testFunction(arg1, arg2) {
alert(arg1);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="dv_Test"></div>








share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54005968%2fpassing-arguments-in-onclick-functions-appended-from-javascript%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown
























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    5














    The issue is because the arg1 value is a string and needs to have quotes around it:






    $(document).ready(function() {
    var agr1 = '#19865 - testArg';
    var arg2 = 1856
    $('#dv_Test').append('<button onclick="testFunction('' + agr1 + '',' + arg2 + ')">Test</button>')
    });

    function testFunction(arg1, arg2) {
    alert(arg1);
    }

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="dv_Test"></div>





    However a much better way to do this would be to put those values in data attributes and add a single delegated event handler to handle all dynamically created buttons. Try this:






    $(document).ready(function() {
    var agr1 = '#19865 - testArg';
    var arg2 = 1856
    var $div = $('#dv_Test').append('<button data-arg1="' + agr1 + '" data-arg2="' + arg2 + '">Test</button>');

    $div.on('click', 'button', function() {
    var $btn = $(this);
    console.log($btn.data('arg1'), $btn.data('arg2'));
    });
    });

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="dv_Test"></div>








    share|improve this answer
























    • thanks the second solution is really good and I will implement that.

      – user6656728
      Jan 2 at 12:08











    • No problem, glad to help

      – Rory McCrossan
      Jan 2 at 13:12
















    5














    The issue is because the arg1 value is a string and needs to have quotes around it:






    $(document).ready(function() {
    var agr1 = '#19865 - testArg';
    var arg2 = 1856
    $('#dv_Test').append('<button onclick="testFunction('' + agr1 + '',' + arg2 + ')">Test</button>')
    });

    function testFunction(arg1, arg2) {
    alert(arg1);
    }

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="dv_Test"></div>





    However a much better way to do this would be to put those values in data attributes and add a single delegated event handler to handle all dynamically created buttons. Try this:






    $(document).ready(function() {
    var agr1 = '#19865 - testArg';
    var arg2 = 1856
    var $div = $('#dv_Test').append('<button data-arg1="' + agr1 + '" data-arg2="' + arg2 + '">Test</button>');

    $div.on('click', 'button', function() {
    var $btn = $(this);
    console.log($btn.data('arg1'), $btn.data('arg2'));
    });
    });

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="dv_Test"></div>








    share|improve this answer
























    • thanks the second solution is really good and I will implement that.

      – user6656728
      Jan 2 at 12:08











    • No problem, glad to help

      – Rory McCrossan
      Jan 2 at 13:12














    5












    5








    5







    The issue is because the arg1 value is a string and needs to have quotes around it:






    $(document).ready(function() {
    var agr1 = '#19865 - testArg';
    var arg2 = 1856
    $('#dv_Test').append('<button onclick="testFunction('' + agr1 + '',' + arg2 + ')">Test</button>')
    });

    function testFunction(arg1, arg2) {
    alert(arg1);
    }

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="dv_Test"></div>





    However a much better way to do this would be to put those values in data attributes and add a single delegated event handler to handle all dynamically created buttons. Try this:






    $(document).ready(function() {
    var agr1 = '#19865 - testArg';
    var arg2 = 1856
    var $div = $('#dv_Test').append('<button data-arg1="' + agr1 + '" data-arg2="' + arg2 + '">Test</button>');

    $div.on('click', 'button', function() {
    var $btn = $(this);
    console.log($btn.data('arg1'), $btn.data('arg2'));
    });
    });

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="dv_Test"></div>








    share|improve this answer













    The issue is because the arg1 value is a string and needs to have quotes around it:






    $(document).ready(function() {
    var agr1 = '#19865 - testArg';
    var arg2 = 1856
    $('#dv_Test').append('<button onclick="testFunction('' + agr1 + '',' + arg2 + ')">Test</button>')
    });

    function testFunction(arg1, arg2) {
    alert(arg1);
    }

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="dv_Test"></div>





    However a much better way to do this would be to put those values in data attributes and add a single delegated event handler to handle all dynamically created buttons. Try this:






    $(document).ready(function() {
    var agr1 = '#19865 - testArg';
    var arg2 = 1856
    var $div = $('#dv_Test').append('<button data-arg1="' + agr1 + '" data-arg2="' + arg2 + '">Test</button>');

    $div.on('click', 'button', function() {
    var $btn = $(this);
    console.log($btn.data('arg1'), $btn.data('arg2'));
    });
    });

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="dv_Test"></div>








    $(document).ready(function() {
    var agr1 = '#19865 - testArg';
    var arg2 = 1856
    $('#dv_Test').append('<button onclick="testFunction('' + agr1 + '',' + arg2 + ')">Test</button>')
    });

    function testFunction(arg1, arg2) {
    alert(arg1);
    }

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="dv_Test"></div>





    $(document).ready(function() {
    var agr1 = '#19865 - testArg';
    var arg2 = 1856
    $('#dv_Test').append('<button onclick="testFunction('' + agr1 + '',' + arg2 + ')">Test</button>')
    });

    function testFunction(arg1, arg2) {
    alert(arg1);
    }

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="dv_Test"></div>





    $(document).ready(function() {
    var agr1 = '#19865 - testArg';
    var arg2 = 1856
    var $div = $('#dv_Test').append('<button data-arg1="' + agr1 + '" data-arg2="' + arg2 + '">Test</button>');

    $div.on('click', 'button', function() {
    var $btn = $(this);
    console.log($btn.data('arg1'), $btn.data('arg2'));
    });
    });

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="dv_Test"></div>





    $(document).ready(function() {
    var agr1 = '#19865 - testArg';
    var arg2 = 1856
    var $div = $('#dv_Test').append('<button data-arg1="' + agr1 + '" data-arg2="' + arg2 + '">Test</button>');

    $div.on('click', 'button', function() {
    var $btn = $(this);
    console.log($btn.data('arg1'), $btn.data('arg2'));
    });
    });

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="dv_Test"></div>






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Jan 2 at 12:02









    Rory McCrossanRory McCrossan

    249k29216253




    249k29216253













    • thanks the second solution is really good and I will implement that.

      – user6656728
      Jan 2 at 12:08











    • No problem, glad to help

      – Rory McCrossan
      Jan 2 at 13:12



















    • thanks the second solution is really good and I will implement that.

      – user6656728
      Jan 2 at 12:08











    • No problem, glad to help

      – Rory McCrossan
      Jan 2 at 13:12

















    thanks the second solution is really good and I will implement that.

    – user6656728
    Jan 2 at 12:08





    thanks the second solution is really good and I will implement that.

    – user6656728
    Jan 2 at 12:08













    No problem, glad to help

    – Rory McCrossan
    Jan 2 at 13:12





    No problem, glad to help

    – Rory McCrossan
    Jan 2 at 13:12













    1














    You need to have quotes around the argument.Alternatively you can try template literals






    $(document).ready(function() {
    var agr1 = '#19865 - testArg';
    var arg2 = 1856
    $('#dv_Test').append(`<button onclick="testFunction('${agr1}','${arg2}' )">Test</button>`)
    });

    function testFunction(arg1, arg2) {
    alert(arg1);
    }

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div id="dv_Test"></div>








    share|improve this answer




























      1














      You need to have quotes around the argument.Alternatively you can try template literals






      $(document).ready(function() {
      var agr1 = '#19865 - testArg';
      var arg2 = 1856
      $('#dv_Test').append(`<button onclick="testFunction('${agr1}','${arg2}' )">Test</button>`)
      });

      function testFunction(arg1, arg2) {
      alert(arg1);
      }

      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <div id="dv_Test"></div>








      share|improve this answer


























        1












        1








        1







        You need to have quotes around the argument.Alternatively you can try template literals






        $(document).ready(function() {
        var agr1 = '#19865 - testArg';
        var arg2 = 1856
        $('#dv_Test').append(`<button onclick="testFunction('${agr1}','${arg2}' )">Test</button>`)
        });

        function testFunction(arg1, arg2) {
        alert(arg1);
        }

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <div id="dv_Test"></div>








        share|improve this answer













        You need to have quotes around the argument.Alternatively you can try template literals






        $(document).ready(function() {
        var agr1 = '#19865 - testArg';
        var arg2 = 1856
        $('#dv_Test').append(`<button onclick="testFunction('${agr1}','${arg2}' )">Test</button>`)
        });

        function testFunction(arg1, arg2) {
        alert(arg1);
        }

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <div id="dv_Test"></div>








        $(document).ready(function() {
        var agr1 = '#19865 - testArg';
        var arg2 = 1856
        $('#dv_Test').append(`<button onclick="testFunction('${agr1}','${arg2}' )">Test</button>`)
        });

        function testFunction(arg1, arg2) {
        alert(arg1);
        }

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <div id="dv_Test"></div>





        $(document).ready(function() {
        var agr1 = '#19865 - testArg';
        var arg2 = 1856
        $('#dv_Test').append(`<button onclick="testFunction('${agr1}','${arg2}' )">Test</button>`)
        });

        function testFunction(arg1, arg2) {
        alert(arg1);
        }

        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <div id="dv_Test"></div>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jan 2 at 12:06









        brkbrk

        29.1k32243




        29.1k32243






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54005968%2fpassing-arguments-in-onclick-functions-appended-from-javascript%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            MongoDB - Not Authorized To Execute Command

            How to fix TextFormField cause rebuild widget in Flutter

            in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith