HTML entities from AJAX into input fields using jQuery

categories: jquery, troubleshooting

I was receiving a JSON string that contained an HTML entity, like this:

 
{ myValue: '€30,000' }
 

I was supposed to put the value of myValue into a text input. I assigned the value to a variable and tried:

 
$('#myInput').val(myValue);
 

but that was putting the string, literally, into the input:

€30,000

— this in spite of the fact that this works just fine:

 
<input type="text" value="&euro;30,000" />
 

I'm not sure if this is a case of jQuery getting a little overzealous in its helpfulness or what — some Googling didn't turn up much, and I needed to move on. So here's what I did:

 
$('body').append('
<div id="temp"></div>
 
');
 
// each time an input needs to be updated ...
$('#temp').html(foo);
$('#myInput').val($('#temp').html());
 

It's a little hacky, but not so hacky that I feel bad about it, and I guess I'm telling myself that its hacky-ness is not very heavy, and it's outweighed by the time I'd have had to spend to solve the root problem.

5 Responses to “HTML entities from AJAX into input fields using jQuery”

  1. James says:
    December 20th, 2007 at 8:56 pm

    Nice work around :)

  2. Aidan says:
    August 29th, 2008 at 10:23 am

    Did you ever learn more about this?

    I need to transfer a string from the server side to the client using JSON. Should that string have html entities encoded before it’s sent? Should it have entities encoded after it’s received and before it’s put into a page? Should it be encoded at all?

    I can’t find any resources on this :¬(

  3. yinyang78 says:
    September 26th, 2008 at 7:42 am

    I’m not sure if this would work, but have you tried this?:

    $(’#myInput’).val(myValue)

  4. yinyang78 says:
    September 26th, 2008 at 7:43 am

    sorry, i hit submit before finishing…..

    this is what i meant to post:

    $(’#myInput’).val(myValue).html();

  5. Mathieu Laurent says:
    April 1st, 2009 at 9:09 am

    A solution :

    if ( foo.search(/&.*;/) != -1 ) {
    foo = $(”<div></div>”).html(foo).html();
    }

Comment