deeej
deeej

Reputation: 387

Handle apostrophe in input field

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?

Upvotes: 2

Views: 2494

Answers (2)

choz
choz

Reputation: 17848

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.

Upvotes: 2

Harshana
Harshana

Reputation: 5476

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>

Upvotes: 0

Related Questions