0

I have a String "Magic Word". I need to use it as value in html checkbox generated by javascript.

in javascript

var itemValue= "Magic task";
var opt = "<input type='checkbox' name='test' id='test' value="+ itemValue+ "/>"+itemValue+ "<br />";
alert(opt); 
$(optionDiv).append(opt);

In alert it is displaying the actual value but after submitting form i am getting only first word as value.It is ignoring second word.

Thanks Ravi Kant

1
  • 1
    Nipick: You really should be using a label element for the text after the input. Commented May 21, 2013 at 13:36

3 Answers 3

6

You need to wrap the value with single quotes:

"<input type='checkbox' name='test' id='test' value='" + itemValue + "' />"
Sign up to request clarification or add additional context in comments.

Comments

1

If you are using jQuery (as I see the usage of $ in your code), it's better to do it with jQuery itself:

var itemValue= "Magic Word";
var opt = $('<input>').attr({
    type: 'checkbox',
    name: 'test',
    id: 'test',
    value: itemValue
});

It will prevent any furthur error, for example if you have some ' in your string:

var itemValue= "Magician's Word";

3 Comments

You also need to create a break tag and the textNode. ;)
@epascarello Yes, you are right, but it has another benefits, preventing errors when the string has ' inside it, and the reading of code will be easier.
itemValue = itemValue.replace(/'/g,"@apos;");
1

When you do not use quotes the attributes value ends at the whitespace. Your rendered string appears as

<input type='checkbox' name='test' id='test' value=Magic Word />

So the parser sees

value=Magic

and an attribute Word with no value. You can see that with the coloring in the post above.

You need to add single quotes around the value

var opt = "<input type='checkbox' name='test' id='test' value='" + itemValue + "' />"+ itemValue+ "<br />";
                                                              ^                 ^

Where does this fail? If you have a ' in your string. You would need to add a replace method and swap it for @apos;

itemValue = itemValue.replace(/'/g,"@apos;"); 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.