2

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?

deeej
  • 357
  • 1
  • 6
  • 22

2 Answers2

2

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.

choz
  • 17,242
  • 4
  • 53
  • 73
0

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>
Harshana
  • 5,151
  • 1
  • 17
  • 27