2

I am very new to HTML/JS so I appologize if this is a basic question... I tried to look this up on the web and was unable to find a solution.

I am using a JS code to create an HTML. I am trying to set a "value" attribute with a var containing spaces (string with spaces). when inspecting the value in chrome I can see that the string is not set correctly.

This is my JS code:

var templateArray = templateString.split("\t");
for (var i = 0; i < templateArray.length; i++) {
  htmlTemplate.push("<option value="+templateArray[i]+">"+templateArray[i]+"</option>");
}

This is the templateArray:

templateArray[0] = template_member_information
templateArray[1] = template - member information

This is what I get when inspecting in chrome:

<option value="template" -="" member="" information="">template - member information</option>
<option value="template_member_information">template_member_information</option>
1
  • 1
    should templateArray[1] = template - member information be templateArray[1] = "template - member information" or what are you doing here? Commented Jan 13, 2013 at 11:54

3 Answers 3

2

Don't write raw HTML, instead store only the values, then create the DOM elements on the fly.

Assuming you have all the values inside array named values have such code to populate a drop down list with items having those values: (and text equal to the value)

var oDDL = document.getElementById("MyDropDownList");
for (var i = 0; i < values.length; i++) {
    var option = new Option();
    option.value = option.text = values[i];
    oDDL.appendChild(option);
}

This way you don't have to mess around with quotes and the code is more flexible.

Live test case.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much! looks much cleaner.
1

Why don't you simply put your value between quotes ?

htmlTemplate.push("<option value=\""+templateArray[i]+"\">"+templateArray[i]+"</option>");

Note that this would still fail with values containing quotes, but there would be less failings.

1 Comment

well, and let's hope templateArray[i] doesn't contain quotes or <>s.
1

You forgot the quotes:

var str = "<option value='"+templateArray[i]+"'>"+templateArray[i]+"</option>";
htmlTemplate.push(str);

1 Comment

Thanks! I forgot the "'" as mentioned here. (I'm sorry)

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.