Context
I'm creating a tiny jQuery script : By clicking on a word, user can erase it and rewrite what he wants.
Original world is in a <span>. When clicked, the <span>is replaced by an <input>.
no <form>, no submit button, only this <input>.
My problem
When pressing enter key to validate the <input>, the rest of my code works well, except for javascript injection :
<input type="text" value="<script>alert('Evil Script')</script>">
My question
What is the best method to prevent my <input> from executing this evil script when pressing enter key?
Please forgive my ingenuous question, and thank you for your advice.
My wrong code
jQuery(document).ready(function($) {
initNom();
function initNom() {
var nomPerso = $('#nomPerso');
var cheminNom = localStorage.getItem('userName');
montrerNom();
nomPerso.on('click', function() {
$(this).replaceWith(
$('<input id="nomPerso" type="text" value="" placeholder="' + nomPerso.text() + '">')
);
$("#nomPerso")
.focus()
.on('keypress', function (e) {
if(e.which === 13) {
e.preventDefault();
//Disable textbox to prevent multiple submit
$(this).attr("disabled", "disabled");
sauverNom();
montrerNom();
$(this).replaceWith($('<span id="nomPerso">' + localStorage.getItem('userName') + '</span>'));
$(this).removeAttr("disabled");
initNom();
}
});
});
function sauverNom() {
var nom = $('#nomPerso').val();
if (typeof(Storage) !== "undefined" && nom) {
localStorage.setItem('userName', nom);
}
}
function montrerNom() {
if (!cheminNom) {
nomPerso.text('{Inserer_nom}');
} else {
nomPerso.text(cheminNom);
}
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nomPerso"><script>alert('Evil Script')</script></div>
Also on CodePen: https://codepen.io/LaBriqueHurlante/pen/mwxjRL