298

I would like to pass a parameter (i.e. a string) to an Onclick function.

For the moment, I do this:

'<input type="button" onClick="gotoNode(' + result.name + ')" />'

with result.name for example equal to string "Add".

When I click on this button, I have an error that says that "Add is not defined". Since this function call works perfectly with a numeric parameter, I assume that it has something to do with the symbols "" in the string.

How can I fix this problem?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JasperTack
  • 4,337
  • 5
  • 27
  • 39
  • 2
    It might be better in this case to simply not use inline event handlers. – Felix Kling Mar 10 '12 at 02:09
  • 1
    Your problem is due to the variable not being escaped properly. Check [my answer](http://stackoverflow.com/a/9643494/295264) – Starx Mar 10 '12 at 02:43

27 Answers27

445

It looks like you're building DOM elements from strings. You just need to add some quotes around result.name:

'<input type="button" onClick="gotoNode(\'' + result.name + '\')" />'

You should really be doing this with proper DOM methods though.

var inputElement = document.createElement('input');
inputElement.type = "button"
inputElement.addEventListener('click', function(){
    gotoNode(result.name);
});

​document.body.appendChild(inputElement);​

Just be aware that if this is a loop or something, result will change before the event fires and you'd need to create an additional scope bubble to shadow the changing variable.

Community
  • 1
  • 1
david
  • 17,925
  • 4
  • 43
  • 57
56

A couple of concerns for me with respect to using string escape in onClick and as the number of arguments grow, it will become cumbersome to maintain.

The following approach will have a one hop - On click - take the control to a handler method and handler method, based on the event object, can deduct the click event and corresponding object.

It also provides a cleaner way to add more arguments and have more flexibility.

<button type="button"
        className="btn btn-default"
        onClick="invoke"
        name='gotoNode'
        data-arg1='1234'>GotoNode</button>

In the JavaScript layer:

  invoke = (event) => {
    let nameOfFunction = this[event.target.name];
    let arg1 = event.target.getAttribute('data-arg1');
    // We can add more arguments as needed...
    window[nameOfFunction](arg1)
    // Hope the function is in the window.
    // Else the respective object need to be used
    })
  }

The advantage here is that we can have as many arguments (in above example, data-arg1, data-arg2, etc.) as needed.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sairam Krish
  • 10,158
  • 3
  • 55
  • 67
  • 4
    I'm surprised this isn't getting more upvotes as it is the cleaner method of passing arguments to an event handler. – Tim O'Brien Sep 30 '16 at 16:47
  • 2
    This does not work, `invoke` is not called when you click on the button – tanguy_k May 07 '19 at 09:10
  • Great solution! If you need to pass Arrays or Objects just use `JSON.stringify(obj)` in the HTML and `JSON.parse(event.target.getAttribute('data-arg'))` in the JavaScript-layer – leonheess Jul 04 '19 at 08:25
  • @SairamKrish In my case, if i click the button i have set to display id, screenshot : https://snag.gy/7bzEWN.jpg code : https://www.pastiebin.com/5d35674e2fc31 – Gem Jul 22 '19 at 07:36
  • This may work, but it is an abstruse, atypical implementation that would be hard to follow for another developer that needed to maintain this. – Spencer Sullivan Sep 09 '19 at 23:17
31

I suggest not even using HTML onclick handlers, and use something more common such as document.getElementById.

HTML:

<input type="button" id="nodeGoto" />

JavaScript:

document.getElementById("nodeGoto").addEventListener("click", function() {
    gotoNode(result.name);
}, false);
Kevin Ji
  • 10,479
  • 4
  • 40
  • 63
  • 3
    `onclick` is not a function, it's a property you have to assign a function to: `....onclick = function() {...};` – Felix Kling Mar 10 '12 at 02:16
  • @FelixKling Thanks for that, my head's still in jQuery mode. – Kevin Ji Mar 10 '12 at 02:18
  • 5
    You're assuming there will be just one of these inputs. – Madbreaks Mar 10 '12 at 02:18
  • Well the OP's question implies that there will only be one input. – Kevin Ji Mar 10 '12 at 02:18
  • I think this option doesn't work for me, because I generate multiple buttons as a result of a search-operation. I could solve this by using a counter to add to the id's but I want to keep it simple and keep it inline – JasperTack Mar 10 '12 at 02:26
  • @kevinji In my case, if i click the button i have set to display id, screenshot : https://snag.gy/7bzEWN.jpg code : https://www.pastiebin.com/5d35674e2fc31 – Gem Jul 22 '19 at 07:36
26

This is a nice and neat way to send a value or object.

<!DOCTYPE html>
<html>
    <body>
        <h1  onclick="test('wow',this)">Click on this text!</h1>
        <script>
            var test = function(value,object) {
                object.innerHTML= value;
            };
        </script>
    </body>
</html>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
zokaee hamid
  • 522
  • 5
  • 16
23

I am guessing, you are creating a button using JavaScript itself. So, the error in your code is that, it will render in this form

<input type="button" onClick="gotoNode(add)" />'

At this current state, add will be considered as an identifier like variables or function calls. You should escape the value like this

'<input type="button" onClick="gotoNode(\'' + result.name + '\')" />'
Starx
  • 77,474
  • 47
  • 185
  • 261
13

Try this...

HTML:

<button id="a1" type="button" onclick="return a1_onclick('a1')">a1</button>

JavaScript:

<script language="javascript" type="text/javascript">
    function a1_onclick(id) {
        document.getElementById(id).style.backgroundColor = "#F00";
    }
</script>

Note: be sure of sending arguments between ' ' signs like ('a1') in HTML code

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mawardy
  • 3,618
  • 2
  • 33
  • 37
  • thanks!! been looking for this prob for couple hourss – cweitat Jan 26 '18 at 07:31
  • Does anyone help? In my case, if i click the button i have set to display id, screenshot : https://snag.gy/7bzEWN.jpg code : https://www.pastiebin.com/5d35674e2fc31 – Gem Jul 22 '19 at 07:37
12

If your button is generated dynamically:

You can pass string parameters to JavaScript functions like the below code:

I passed three parameters where the third one is a string parameter.

var btn ="<input type='button' onclick='RoomIsReadyFunc("+ID+","+RefId+",\""+YourString+"\");'  value='Room is Ready' />";

// Your JavaScript function

function RoomIsReadyFunc(ID, RefId, YourString)
{
  alert(ID);
  alert(RefId);
  alert(YourString);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MJ X
  • 8,506
  • 12
  • 74
  • 99
10

Also you can use the grave accent symbol ( ` ) in a string

Try:

`<input type="button" onClick="gotoNode('${result.name}')" />`

For more information, visit MDN and Stack Overflow.

By Chrome, Edge, Firefox (Gecko), Opera, Safari support, but it does not support Internet Explorer.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MJ Vakili
  • 2,798
  • 1
  • 19
  • 25
7

If the requirement is to reference the global object (JavaScript) in your HTML code, you can try this. [Don't use any quotes (' or ") around the variable]

Fiddle reference.

JavaScript:

var result = {name: 'hello'};
function gotoNode(name) {
    alert(name);
}

HTML:

<input value="Hello" type="button" onClick="gotoNode(result.name)" />​
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Sandeep G B
  • 3,957
  • 4
  • 26
  • 43
  • I get an error when I try this solution: the part "+ result.name +" is used as string in this case – JasperTack Mar 10 '12 at 02:28
  • what is "result" object? Is it a global variable declared in JS? like ... var result = {name: 'javascript'}; – Sandeep G B Mar 10 '12 at 02:30
  • result contains a record from the jowl library: it's a json-structure with attributes name, type, ... – JasperTack Mar 10 '12 at 02:36
  • Jaspack, I have updated the answer. Does it work for you now? – Sandeep G B Mar 10 '12 at 02:37
  • Thank you for the example, but that doesn't work in my case: the result variable isn't global, but is a variable within a procedure. So when I call the function with result.name, result isn't known – JasperTack Mar 10 '12 at 02:45
5

Multiple parameters:

bounds.extend(marker.position);
bindInfoWindow(marker, map, infowindow,
    '<b>' + response[i].driver_name + '</b><br>' +
    '<b>' + moment(response[i].updated_at).fromNow() + '</b>
     <button onclick="myFunction(\'' + response[i].id + '\',\'' + driversList + '\')">Click me</button>'
);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Zahidur Rahman
  • 1,688
  • 2
  • 20
  • 30
2

You can pass a reference or string value. Just put the function inside the double commas "" as per the below snapshot:

Enter image description here

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abdul Khaliq
  • 2,139
  • 4
  • 27
  • 31
1

If to use for generation of a set of buttons with different parameters of handlers.

JavaScript Closures

let some_button = document.createElement( "button" );
some_button.type = "button";

some_button.onclick = doWithParam( some_param );

function doWithParam( param ){
    return function(){
        alert( param ); // <-- Your code here
    }
}

If we do:

some_button.onclick = foo( some_param );
function foo( param ){
    alert( param );
}

then function foo starts after every updating page.

If we do:

for( let i = 0; i < 10; ++i ){
    var inputElement = document.createElement('input');
    inputElement.type = "button"
    inputElement.addEventListener('click', function(){
        gotoNode(result.name);
    });

 ​   document.body.appendChild(inputElement);​
}

then for all buttons created in the loop, the last value of the parameter is "result.name".

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

Here is a jQuery solution that I'm using.

jQuery

$("#slideshow button").click(function(){
    var val = $(this).val();
    console.log(val);
});

HTML

<div id="slideshow">
    <img src="image1.jpg">
    <button class="left" value="back">&#10094;</button>
    <button class="right" value="next">&#10095;</button>
</div>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

If you need to pass a variable along with the 'this' keyword, the below code works:

var status = 'Active';
var anchorHTML = '<a href ="#" onClick = "DisplayActiveStatus(this,\'' + status + '\')">' + data+ '</a>';
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Arun
  • 11
  • 1
1
<!----  script ---->
<script>
function myFunction(x) {
  document.getElementById("demo").style.backgroundColor = x; 
}
</script>

<!---- source ---->
<p id="demo" style="width:20px;height:20px;border:1px solid #ccc"></p>

<!----  buttons & function call ----> 
<a  onClick="myFunction('red')" />RED</a> 
<a  onClick="myFunction('blue')" />BLUE</a> 
<a  onClick="myFunction('black')" />BLACK</a>
hariharan
  • 21
  • 2
  • 2
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Tyler2P Jan 06 '21 at 12:24
1

This is work for me:

$(element).attr("onClick", 'functionName(' + "\"" + Object.attribute + "\"" + ')');

Just add \ slash in ()

※Multiple parameters example

"functionName(" + "'" + parameter1 + "','" + parameter2 + "','" + parameter3 + "','" + parameter4 + "','" + parameter5 + "','" + parameter6 + "')"
Creek
  • 207
  • 2
  • 12
0

For passing multiple parameters you can cast the string by concatenating it with the ASCII value. Like, for single quotes we can use &#39;:

var str = "&#39;" + str + "&#39;";

The same parameter you can pass to the onclick() event. In most of the cases it works with every browser.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
PVIJAY
  • 73
  • 8
0
<style type="text/css">
    #userprofile{
        display: inline-block;
        padding: 15px 25px;
        font-size: 24px;
        cursor: pointer;
        text-align: center;
        text-decoration: none;
        outline: none;
        color: #FFF;
        background-color: #4CAF50; // #C32836
        border: none;
        border-radius: 15px;
        box-shadow: 0 9px #999;
        width: 200px;
        margin-bottom: 15px;
    }
    #userprofile:hover {
        background-color: #3E8E41
    }

    #userprofile:active {
        background-color: #3E8E41;
        box-shadow: 0 5px #666;
        transform: translateY(4px);
    }

    #array {
        border-radius: 15px 50px;
        background: #4A21AD;
        padding: 20px;
        width: 200px;
        height: 900px;
        overflow-y: auto;
    }
</style>
if (data[i].socketid != "") {
    $("#array").append("<button type='button' id='userprofile' class='green_button' name=" + data[i]._id + " onClick='chatopen(name)'>" + data[i].username + "</button></br>");
}
else {
    console.log('null socketid  >>', $("#userprofile").css('background-color'));
    //$("#userprofile").css('background-color', '#C32836 ! important');

    $("#array").append("<button type='button' id='userprofile' class='red_button' name=" + data[i]._id + " onClick='chatopen(name)'>" + data[i].username+"</button></br>");
    $(".red_button").css('background-color','#C32836');
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jay Jariwala
  • 185
  • 2
  • 10
0

If you are using ASP.NET you can use JavaScript:

HTML

<input type='button' value='test' onclick='javascript: EditSelectedOptionName(x,y)' />"

JavaScript

function EditSelectedOptionName(id, name) {
    console.log(id);
    console.log(name);
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abdullah Tahan
  • 1,963
  • 17
  • 28
0

If you are adding buttons or link dynamically and facing the issue then this may be help. I solved it by this way:

var link= $(contentData1[i]).find("td:first font b a").attr("href",'javascript:onClick=openWin(\'' + tdText + '\')');

I am new to HTML, jQuery and JavaScript. So maybe my code will not be optimized or syntax, but it was working for me.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Avinash Verma
  • 2,572
  • 1
  • 18
  • 22
0

In Razor, you can pass parameters dynamically:

<a href='javascript:void(0);' onclick='showtotextbox(@Model.UnitNameVMs[i].UnitNameID, "@Model.UnitNameVMs[i].FarName","@Model.UnitNameVMs[i].EngName","@Model.UnitNameVMs[i].Symbol" );'>@Model.UnitNameVMs[i].UnitNameID</a>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ghadir Farzaneh
  • 429
  • 5
  • 6
0

You can use this:

'<input id="test" type="button" value="' + result.name + '" />'

$(document).on('click', "#test", function () {
    alert($(this).val());
});

It worked for me.

AgungCode.Com
  • 677
  • 6
  • 9
0
let task = {....}

<button onclick="myFunction('${task}')">Continue task</button></li>
Mirco
  • 2,940
  • 5
  • 34
  • 57
Mario Callejas
  • 101
  • 1
  • 2
0

Not escaping double quotes is the cause of OP's problem. A readable approach to escape double quotes is using backticks (MDN). Here is a sample solution:

my_btn.setAttribute('onclick', `my_func("${onclick_var1}", "${onclick_var2}")`);

Niket
  • 21
  • 2
0
<button style="background-color: gray;color:white;" onclick="displayAlert('the message')">alert</button>
<script>
    function displayAlert(msg){
        alert(msg);
    }

</script>
Andam Adam
  • 21
  • 2
  • 2
    When answering you should include a description of your code so that others can understand how it addresses the question as asked. – Besworks Jun 01 '22 at 19:23
-1

You can use this code in your button onclick method:

<button class="btn btn-danger" onclick="cancelEmployee(\''+cancelButtonID+'\')" > Cancel </button>
Shujat Munawar
  • 1,657
  • 19
  • 23
-1

The following works for me very well,

<html>
<head>
    <title>HTML Form</title>
</head>
<body>
    <form>
        <input type="button" value="ON" onclick="msg('ON')">
        <input type="button" value="OFF" onclick="msg('OFF')">
    </form>
    <script>
        function msg(x){
            alert(x);
        }
    </script>
</body>
</html>