Note that there are some explanatory texts on larger screens.

plurals
  1. POCombo box populates a text field - JavaScript and user input
    primarykey
    data
    text
    <h2>Setup</h2> <p>What I need in the end: a combo box and a text field. Selecting an item from the combo box populates a value in the text field. Items in the combo box come from user input.</p> <p>This is my current code that works nice:</p> <pre><code>function fill() { var select = document.getElementById("select"); var value = select.options[select.selectedIndex].value; var textfield = document.getElementById("textfield"); switch (value) { case "1": textfield.value = "some user-provided text"; break; case "2": textfield.value = "containing possibly &lt; &gt; &amp; etc."; break; } } &lt;select id="select" onchange="fill()"&gt; &lt;option&gt;Select something...&lt;/option&gt; &lt;option value="1"&gt;Select option 1&lt;/option&gt; &lt;option value="2"&gt;Select option 2&lt;/option&gt; &lt;/select&gt; &lt;input type="text" id="textfield"/&gt; </code></pre> <h2>Problem</h2> <p>I am not sure what to do if the user-provided text to populate contains dangerous characters. Usually I would HTML-encode it before writing it in the HTML code, but now I am writing it into JavaScript code.</p> <p>All of the JavaScript is generated by a Java backend. I can't really create it like this:</p> <pre><code>String value = getValueFromUser(); write("textfield.value = \"" + value + "\";"); </code></pre> <p>Because then someone would enter <code>"; somethingBad(); //</code> and some other user would on selecting this option get <code>somethingBad()</code> executed.</p> <p>If I HTML-encode the value:</p> <pre><code>String value = htmlEncode(getValueFromUser()); write("textfield.value = \"" + value + "\";"); </code></pre> <p>Then (security questions aside) after selecting a value in the combo box the text field will be populated with HTML-encoded text.</p> <h2>Question</h2> <p>How do I encode the user-provided values so that:</p> <ul> <li>They cannot be misused for JavaScript code injection, and</li> <li>They look the same after being populated into the text field?</li> </ul>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload