Lolly
Lolly

Reputation: 36422

Using JavaScript to bind onclick event with arguments

I am using JavaScript to create a button element and binding onclick event to it. I am using the below code:

function getElement (rowObject )
       {
          var element ='<div id="deptNmBtn"><button onClick=getDepartMentNm("' +   rowObject.empName+'")> <span>Add</span></button></div>';
          return element;
       }

But here I am passing a parameter Employee Name. The code works if employee name is passed as a single string without any spaces but when passed with spaces its throwing JavaScript error.

SyntaxError: unterminated string literal

Have anyone faced this error? Any help will be really appreciated.

Upvotes: 0

Views: 2165

Answers (2)

Teemu
Teemu

Reputation: 23406

There is a quoting problem in your code. Try this:

var element = '<div id="deptNmBtn"><button onClick="getDepartMentNm(\'' + rowObject.empName + '\')" ><span>Add</span></button></div>';

As you can see, the value for onClick is unquoted. Browsers can parse unquoted attributes, but then they are expected to end up to a space. Actually your parsed code looks like this:

<button onClick=getDepartMentNm("Employer Name")>

HTML parser cuts the function call from the first space, and Name") is ignored since it can't be regognized as valid HTML. JavaScript is executed from "right to left", and the first thing JS tries to do is to get a valid string for function argument. Now HTML parser has cut the function, and JS can't find closing quote, so it throws an error.

Upvotes: 0

Jo&#227;o Silva
Jo&#227;o Silva

Reputation: 91329

You need to wrap the inline click handler with ':

function getElement (rowObject) {
  var element = '<div id="deptNmBtn"><button onClick=\'getDepartMentNm("' +   rowObject.empName + '")\' ><span>Add</span></button></div>';
  return element;
}

DEMO.

Upvotes: 1

Related Questions