开发者

How do I fix JS 'unterminated string literal' error

开发者 https://www.devze.com 2023-04-11 11:44 出处:网络
I have a form on m开发者_开发百科y site that runs some basic JS validation when the user clicks submit, before the form is submitted, but I am getting an error \'unterminated string literal\' when che

I have a form on m开发者_开发百科y site that runs some basic JS validation when the user clicks submit, before the form is submitted, but I am getting an error 'unterminated string literal' when checking some of the fields.

I understand what this error is (users adding line breaks in a textarea in this case) but I cannot think of a way of avoiding/fixing it.

Here is how I declare the form -

<form id="<?php echo $form_name; ?>" 
      name="<?php echo $form_name; ?>" 
      class="standard-form" 
      method="POST" action="" 
      onsubmit="return validate_form('<?php echo $form_name; ?>')">

And here is how I am checking the field that is causing me trouble -

var your_query = document.forms['enquiry']['your_query'].value
if(your_query === ''){
    result = false;
}

Any help here would be appriciated.

Thanks.


My guess is $form_name contains a single quote character: '

First, you should really escape that output with htmlentities and json_encode:

<form id="<?php echo htmlentities($form_name); ?>"
      name="<?php echo htmlentities($form_name); ?>"
      class="standard-form"
      method="POST"
      action=""
      onsubmit="return validate_form(<?php echo htmlentities(json_encode($form_name)); ?>)">

See also Pass a PHP string to a Javascript variable (including escaping newlines)

Next, don't use that onsubmit intrinsic event attribute and don't pass the form name to it; use proper DOM scripting (or jQuery) and event handling in your JavaScript file:

(function() {
    var form = document.getElementById("<?php echo json_encode($form_name); ?>");
    form.addEventListener('submit', onSubmit, false);

    function onSubmit() {
        // manipulate variable `form` as necessary
        // without having to pass around a `form_name`
    }
}());
0

精彩评论

暂无评论...
验证码 换一张
取 消