user500665 user500665 -4 years ago 92
jQuery Question

Get value that contains double quotes

I am trying to set a variable to the value of an input using jQuery then append a new input with that value. The problem is that the value contains double quotes so it messes up the output.

Eg:

<input value="a:1:{s:7:&quot;form&quot;;a:5" />
<div class="test"></div>


jQuery:

$('.test').append('<input type="radio" value="'+ value +'"/>');


Output:

<div class="test"><input value="a:1:{s:7:" form";a:5" type="radio"></div>

Answer Source

The problem is that you're using " as the delimiters arount the value attribute, and that character is also in the value that you're putting there. So those embedded quotes are ending the attribute.

Create the element using object syntax, rather than by concatenating strings, then you don't have to deal with these syntactic details.

$('.test').append($('<input>', {
    value: value
}));

You can also use the .val() function to set the value of the input:

$('.test').append($('<input>').val(value));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download