Why does a space at the end of a value disappear when selecting an item from a datalist?

Viewed 1454

I ran into a curious issue where the space at the end of a value disappears, when using a datalist. It left me wondering why. (I am using google chrome)

I can make sure that the space at the end will be included in the end result by assigning it to a value attribute, instead of inbetween the <option> and </option> tags. JSFiddle that works.

  1. Why does the value in input (#datalist-input) remove the space at the end when selecting the value from the datalist?
  2. Should I use the space inbetween the <option> and </option> tags at all? If so, what for. If not why not and why isn't the <option> tag selfclosing only if this is the case?

JSFiddle link, that removes the space: JSFiddle

html

<h3>The disappearing of a space at the end of a line</h3>
<input id="input" type="text" value="Space at the end " disabled="true">
<datalist id="datalist"></datalist>
<input id="datalist-input" list="datalist">
<h6>(select the only option in the datalist and click somewhere to trigger the script)</h6>

javascript/jQuery

let originalInput = $("#input").val();
$("#datalist").append(`<option>${originalInput}</option>`);
$("#datalist-input").change(function () {
    let datalistText = $("#datalist-input").val();
    if(datalistText !== originalInput) {
        alert(`The original value: "${originalInput}" is not equal to: "${datalistText}"`);
    } else {
        alert(`The original value: "${originalInput}" is equal to: "${datalistText}"`);
    }
}); // end change
1 Answers
Related