1

I am facing a problem like if I click the button nothing is happening. I looked into the Firebug console. It's throwing an error in the second argument that I have passed.

In the second argument the question is a string, so it is enclosed with single quotes, but the value attained from the server side also has single quotes (father's) so (s middle name?') is not considered by JavaScript and throws a syntax error. How do I avoid this?

Source Code:

JSP page code:

<input type="button" id="btnSubmit" Value="Edit" onclick="return
       editSeqQuestion('<%=QuestionId%>','<%=Question%>','<%=QuestionDataType%>',
                       '<%=AudioPath%>','<%=securityQuestionType%>')" />

In browser, view page source:

The code looks like:

<input type="button" id="btnSubmit" Value="Edit" onclick="return
       editSeqQuestion('72','what is your first child's nick name?',
       'Alpha Numeric','nickname.wav','SecurityQuestion')" />

Error: SyntaxError: missing ) after argument list

Firefox Error Console

9
  • 1
    I think you must handle it with your server side template language. Commented Jun 5, 2013 at 3:33
  • Did you try escaping it with a backslash? See stackoverflow.com/questions/242813/… Commented Jun 5, 2013 at 3:33
  • This looks like a duplicate of stackoverflow.com/questions/2004168/javascript-escape-quotes Commented Jun 5, 2013 at 3:34
  • 2
    stringvar.replace("'","\\'"); Commented Jun 5, 2013 at 3:34
  • 1
    Easiest most effective fix: separate your markup from your JavaScript. Done. Commented Jun 5, 2013 at 3:35

4 Answers 4

2

The correct way to handle this is to escape the HTML in your JSP file, and also bind the event unobtrusively. The values from the database can be put in data-* attributes. For example, your HTML would be something like the following. Include this at the top of your JSP:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

Using <c:out /> will encode special characters for correctly outputting into HTML, such as ', ", and & (among others).

And then change your HTML to be:

<input type="button" id="btnSubmit" value="Edit"
       data-question-id="<c:out value="${QuestionId}" />"
       data-question="<c:out value="${Question}" />"
       data-question-data-type="<c:out value="${QuestionDataType}" />"
       data-audio-path="<c:out value="${AudioPath}" />"
       data-security-question-type="<c:out value="${securityQuestionType}" />" />

And your JavaScript:

window.onload = function () {
    document.getElementById("btnSubmit").onclick = function () {
        var questionId = this.getAttribute("data-question-id"),
            question = this.getAttribute("data-question"),
            questionDataType = this.getAttribute("data-question-type"),
            audioPath = this.getAttribute("data-audio-path"),
            securityQuestionType = this.getAttribute("data-security-question-type");
        editSeqQuestion(questionId, question, questionDataType, audioPath, securityQuestionType);
    };
};

Of course, it is "better" to use addEventListener, instead of setting onload and onclick. So you might use this:

function addEvent(element, eventName, callback) {
    if (element.addEventListener) {
        element.addEventListener(eventName, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + eventName, callback);
    }
}

and then bind events like:

addEvent(window, "load", function () {
    addEvent(document.getElementById("btnSubmit"), "click", function () {
        // The code from above
    });
});

Reference:

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

1 Comment

Other than this is verbose, I like this answer too. In fact I have done exactly that (more or less) building elements on the fly server side which contain their own data points in attributes. With jQuery it is incredibly easy to bind and manipulate multiple elements all at once.
0

Yes, you have a few options. Two are the most obvious:

  1. Tackle it server side and have your value come into your page from your JSP already string replaced with an html entity ' being the most logical (then you don't worry about your quote notation.
  2. Abstract it one way or the other into a js variable. Passing a js variable into a function obviates the need to escape the quotes (at least while passing it).

The first option is the least amount of work in some ways. Depending on how dynamic this is supposed to be, you might opt for the second option. In that case, I would suggest the jsp building a nice object or array for you in js which you can then reference (I am guessing you have more than one question set). Have the jsp set a unique id on each element and then have the onclick reference the array by the same id notation to use the object/array stored values as necessary. Go one step farther and bind your function to the elements and follow unobtrusive code methods.

In the short run, your page might end up looking something like this:

<script>
  aQs = [
   {v: 72, q: 'What is child&apos;s name', t: 'AN', s: 'nick.wav', title: 'Sec'},
   {v: 23, q: 'What city', t: 'AN', s: 'city.wav', title: 'Sec'}
  ];

  function edQ(qId) {
    dosomething(aQs[qId]);
  }
</script>

<input type="button" id="btn_0" Value="Edit" onclick="edQ(this.id.split('_')[1])" />
<input type="button" id="btn_1" Value="Edit" onclick="edQ(this.id.split('_')[1])" />

In either case, I think the easiest/safest thing to do to generally handle the ' is to replace it server side with an html entity.

Comments

-1

My suggestion is to just not do that; Instead, call a wrapper function. That way, you don't have to worry about escaping anything.

<script type="text/javascript">
    function editSeqQuestion(...) {
        ...
    }

    function wrapperFunction() {
        editSeqQuestion('72','what is your first child\'s name?',
        'Alpha Numeric','fathersmiddlename.wav','SecurityQuestion');
    }
</script>

<input ... onclick="wrapperFunction();" />

1 Comment

That doesn't help anything. As you can see, the quoting is still wrong. The special characters need to be encoded. And it's better to do something like this, but you probably wouldn't actually print the values in the JavaScript function...you'd put them in data-* attributes
-2

You can escape characters by prepending them with a backslash(\). As a result, any backslash character has to be escaped too (\\).

var x = 'What is your child\'s nick name?';

2 Comments

His jsp has it stored in a variable.
the values are coming from server side so i cant add backslash

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.