developer developer -4 years ago 76
HTML Question

'optgroup' element label isn't reading the string after space

Below when the code runs label doesn't read the string 'data' after space. I have tried with some CSS on optgroup element but it didn't make any change on its label.



var data = "Names of Meters";
var func = function() {
var options =
"<optgroup label=" +data+ ">"
+'<option value="Meter1" >' + "Temperature" + '</option>'
+'<option value="Meter2" >' + "Wave" + '</option>'
+'<option value="Meter3" >' + "Wind Speed" + '</option>'
+ "</optgroup>";
return options
}
document.getElementById("demo").innerHTML = func();

<select type='list' name='sensors' id ="demo" multiple></select>




Answer Source

You missed the quotation marks of label name.

var data = "Names of Meters";
var func = function() {
    // here, surround the 'data' with single quotation marks
    var options = "<optgroup label='" + data + "'>"
        + '<option value="Meter1" >' + "Temperature" + '</option>'
        + '<option value="Meter2" >' + "Wave" + '</option>'
        + '<option value="Meter3" >' + "Wind Speed" + '</option>'
        + "</optgroup>";
    return options;
};
document.getElementById("demo").innerHTML = func();
<select type='list' name='sensors' id ="demo" multiple></select>

But why is it still reading until the white space even if without quotation marks?

Because quotes around attribute values are not necessary. For example, you can use

<input value=4 />

However, sometimes it is necessary to use quotes (like this case). If the value contains a whitespace, it'll not display correctly.

See HTML Attributes

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download