Skip to content Skip to sidebar Skip to footer

Why Does A Space At The End Of A Value Disappear When Selecting An Item From A Datalist?

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 sp

Solution 1:

This happens any time you have leading or trailing whitespace in the text of an option, and no value attribute.

The text of the option is used as the value, and whitespace is trimmed off.

This behaviour is specified in the HTML specification

The value attribute provides a value for element. The value of an option element is the value of the value content attribute, if there is one, or, if there is not, the value of the element's text IDL attribute.

Note that it just says the value is the same as the "text IDL" if no value is set, but for options the "text IDL" is specified as follows

option . text Same as textContent, except that spaces are collapsed.

It specifically says that spaces are collapsed when getting the "text IDL" that is used to set the value attribute if no such attribute is already set on the element, so this is the expected behaviour.

Here's an example showing the difference between letting the text be used as the value, and specifically adding a value attribute :

var t1 = $('#test1 option').get(0),
    t2 = $('#test2 option').get(0);
    
console.log( t1.value, t1.value.length );             // length === 10console.log( t1.textContent, t1.textContent.length ); // length === 12console.log( t2.value, t2.value.length );             // length === 22console.log( t2.textContent, t2.textContent.length ); // length === 22/*
    The option where the text is converted to a value property has a difference in length, the whitespace is trimmed.
    
    The option whith a value attribute, where the text isn't used for the value property, keeps the whitespace, and the length is the same
*/
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><selectid="test1"><option> has spaces </option></select><selectid="test2"><optionvalue=" has spaces and value "> has spaces and value </option></select>

The solution in this case would be to add a value

$("#datalist").append(`<option value="${originalInput}">`);

Post a Comment for "Why Does A Space At The End Of A Value Disappear When Selecting An Item From A Datalist?"