Input field containing double quotes value

Viewed 77445

In my PHP project I have a value containing special characters like ",', etc. (" 5 " inches, '3.5' inches, etc.). But it does not appear in a text field. How can I display this?

Is it possible to display this value in a text box?

8 Answers

Use htmlentities:

<input value="<?php echo htmlentities($value);?>">

I suppose your "text box" is an HTML <input> element?

If so, you are displaying it using something like this:

echo '<input name="..." value="' . $yourValue . '" />';

If it's the case, you need to escape the HTML that's contained in your variable, with htmlspecialchars:

echo '<input name="..." value="' . htmlspecialchars($yourValue) . '" />';

Note that you might have to add a couple of parameters, especially to specify the encoding your are using.


This way, considering $yourValue has been initialized like this :

$yourValue = '5 " inches';

You'll get from this generated HTML:

<input name="..." value="5 " inches" />

To that one, which works much better:

<input name="..." value="5 &quot; inches" />

I've found if you have double quotes in a variable in JavaScript (from Ajax/database whatever) and you want to put it in a field - if you build the whole field/form HTML content and then swap that into a div using innerHTML, the double quotes in the value will cause problems. I was doing this and I couldn't figure a way around it by escaping either.

You should build the HTML content with the field and swap it in first, and then do a document.getElementById('myfieldid').value = thevalue; instead and it works fine.

Related