[javascript] how to add <script>alert('test');</script> inside a text box?

This is strange requirement!

I want to <script>alert('test');</script> in an input type text but it should not execute the alert().

I just need to set the text <script>alert('test');</script>.
Am using nwt framework... And also is this do-able in JS?

Thanks,
Md Waseem

This question is related to javascript node.js

The answer is


is you want fix XSS on input element? you can encode string before output to input field

PHP:

$str = htmlentities($str);

C#:

str = WebUtility.HtmlEncode(str);

after that output value direct to input field:

<input type="text" value="<?php echo $str" />

JQuery version:

$('yourInputSelectorHere').val("<script>alert('test');<\/script>")

Ok to answer this . I simply converted my < and the > to &lt; and &gt;. What was happening previously is i used to set the text <script>alert('1')</script> but before setting the text in the input text browserconverts &lt; and &gt; as < and the >. So hence converting them again to &lt; and &gt;since browser will understand that as only tags and converts them , than executing the script inside <input type="text" />


I want to alert('test'); in an input type text but it should not execute the alert(alert prompt).

<input type="text" value="<script>alert('test');</script>" />

Produces:

enter image description here

You can do this programatically via JavaScript. First obtain a reference to the input element, then set the value attribute.

var inputElement = document.querySelector("input");
inputElement.value = "<script>alert('test');<\/script>";

. I usually do it element.value="<script>alert('test');</script>".

If sounds like you are generating an inline <script> element, in which case the </script> will end the HTML element and cause the script to terminate in the middle of the string.

Escape the / so that it isn't treated as an end tag by the HTML parser:

element.value = "<script>alert('test');<\/script>"