Pregunta

I send data from HTML-Text-Areas to a JSP which inserts them into a database.

If the page is reloaded the database-records are put in this Text-Area and in a JavaScript variable. The variable is used to determine whether the user has changed the value of the Text-Area or not.

The testing procedure in JavaScript is pretty basic and works most of the time:

if(orig_info != document.getElementById('info').value)
//Something has changed!

Now it occurs that in some cases even though nothing has changed the change-procedure is called. I checked the text-area and the variable with firebug and it's the same text. That was odd, so I read the length of both strings:

document.getElementById('info').value.length    231     
orig_info.length                                235

Yet I couldn't see any difference of 4 Characters so I made a simple output: Letter-Number, Letter, Unicode16 of the Letter and got that: First one is the Text-Area: document.getElementById('info').value, second one is the variable orig_bemerkung

61  |.  |\u002E|    61  |.  |\u002E
62  |   |\u000A|    62  |   |\u000D
63  |1  |\u0031|    63  |   |\u000A
                    64  |1  |\u0031

Now I see it's the old problem with \u000D and \u000A.

I don't know how to solve that. On the Server I write the following code:

ret.append("\ndocument.getElementById('info').innerHTML='").append(StringEscapeUtils.escapeJavaScript(this.getInfo())).append("';");

ret.append("orig_info = '").append(StringEscapeUtils.escapeJavaScript(this.getInfo())).append("';\n");

return ret.toString();

Even though, both time exactly the same code is used the Text-Area deals with its content different than the variable. How can i solve my problem that orig_info equals document.getElementById('info').value even though, someone used Enter in the Text-Area before?

¿Fue útil?

Solución

The rules for HTML form posts explicitly state that <textarea> values must be transmitted with CR-LF pairs for hard line breaks typed by the user. Browsers (all of them I think, even newer IE versions) inexplicably return <textarea> values to JavaScript code with hard line breaks indicated with LF alone.

You can account for this weirdness by converting your values yourself. It's something like this:

function realValue( textareaValue ) {
  textareaValue = textareaValue.replace(/([^\r]|^)\n/g, "$1\r\n");
  return textareaValue;
}

// ...

var xmitValue = realValue( someTextArea.value );
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top