简体   繁体   中英

setting a “value” attribute in html with a variable containing spaces

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>

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 .

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.

You forgot the quotes:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM