0

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.

2
  • 4
    How about stepping into this century and replacing those inline handlers with something else. Commented Sep 3, 2012 at 18:59
  • 1
    You've tagged jQuery and yet are not taking advantage of its use. Don't use the onclick attribute, as HTML belongs in .html files, CSS belongs in .css files, and JS belongs in .js files. Commented Sep 4, 2012 at 4:09

2 Answers 2

1

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.

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

1 Comment

Thanks for your answer and I have marked it. But if you try passing the object itself, its not working. In your demo try passing "rowObject" instead of "rowObject.empName" and alert("rowObject.empName") prints undefined.
0

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.

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.