Handle apostrophe in input field

Viewed 732

I have some js that adds an input field for a user:

var user = "O'Conner, John"    
b.innerHTML += "<input type='hidden' value='" + user + "'>";

When its inserted it looks like this:

<input type="hidden" value="O" Conner, John'>

How do I amend this so it outputs like this:

<input type="hidden" value="O'Conner, John">

I need the value to show the full name with the apostrophe. How can I get this to work?

2 Answers

You can escape the value first by replacing it with HTML entities.

As for ' - It can either be &rsquo; or &lsquo;

var user = "O'Conner, John";
user = user.replace("'", "&lsquo;");
document.getElementById("container").innerHTML += "<input type='text' value='" + user + "'>";
<div id="container"></div>

There is also another thread that already answers this question.

When you create an element with JavaScript, you can pass the value to the input without any issue. Please check the below example:

var user = "O'Conner, John"
var b = document.getElementById("b")
var input = document.createElement("input")
input.type = "text"
input.value = user;
b.appendChild(input)
<body id="b"></body>

Related