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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vignesh
  • 1,458
  • 12
  • 31
  • 59
  • 1
    I think you must handle it with your server side template language. –  Jun 05 '13 at 03:33
  • Did you try escaping it with a backslash? See http://stackoverflow.com/questions/242813/when-to-use-double-or-single-quotes-in-javascript?rq=1 – canhazbits Jun 05 '13 at 03:33
  • This looks like a duplicate of http://stackoverflow.com/questions/2004168/javascript-escape-quotes – Tespa42 Jun 05 '13 at 03:34
  • 2
    `stringvar.replace("'","\\'");` – Alexandre Lavoie Jun 05 '13 at 03:34
  • 1
    Easiest most effective fix: separate your markup from your JavaScript. Done. – elclanrs Jun 05 '13 at 03:35
  • Also possible duplicate of http://stackoverflow.com/questions/9708242/how-to-escape-a-single-quote-from-within-a-jsp – Bad Wolf Jun 05 '13 at 03:36
  • Maybe this question will help you (I hope so): http://stackoverflow.com/questions/1470768/how-to-escape-apostrophe-or-quotes-on-a-jsp-used-by-javascript –  Jun 05 '13 at 03:43
  • Encode the values being written to the page. `"` should be `"`, `'` should be `'`. Move these values to `data-*` attributes and bind the event handler unobtrusively. – Ian Jun 05 '13 at 03:54
  • I used this String SecurityQuestion = Question.replace("'","\\'"); code it's working fine now , thanks all – Vignesh Jun 05 '13 at 04:03

4 Answers4

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:

Ian
  • 50,146
  • 13
  • 101
  • 111
  • 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. – williambq Jun 05 '13 at 04:20
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.

williambq
  • 1,125
  • 7
  • 12
-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();" />
Tespa42
  • 567
  • 4
  • 12
  • 1
    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 – Ian Jun 05 '13 at 03:56
-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?';
Doug Miller
  • 1,017
  • 2
  • 7
  • 19