bootstrap5-tags icon indicating copy to clipboard operation
bootstrap5-tags copied to clipboard

First option is unselected on load if placeholder text is missing

Open tim1mw opened this issue 1 month ago • 2 comments

Using the attached test html file with the latest tags.js from the master branch, the first option of any select list will be unselected on load, resulting in this:

Image

When the expected behaviour was for Item 1 and Item 4 to be showing.

Which means that when returning to a form with values pre-selected, the first selected item is always lost on submission if it isn't added back in. The expected behaviour is that the first option remains selected.

The problem seems to be the _getPlaceholder method, which is deliberately un-setting the first option if there is no placeholder.

	_getPlaceholder() {
		// Use placeholder and data-placeholder in priority
		if (this._selectElement.hasAttribute("placeholder")) {
			return this._selectElement.getAttribute("placeholder");
		}
		if (this._selectElement.dataset.placeholder) {
			return this._selectElement.dataset.placeholder;
		}
		// Fallback to first option if no value
		const firstOption = this._selectElement.querySelector("option");
		if (!firstOption || !this._config.autoselectFirst) {
			return "";
		}
		rmAttr(firstOption, "selected");
		firstOption.selected = false;
		return !firstOption.value ? firstOption.textContent : "";
	}

I didn't want any placeholder text for my select, so had omitted the attribute and found this behaviour very confusing until I dived into the code and found the code. I do note that the placeholder attribute is described "Provides a placeholder if none are provided as the first empty option" in the docs, but I would still not have expected the first option to be unselected in this scenario.

I've decided to patch the copy of tags.js I'm using on my site to remove the code that unsets the first option and tries to use attributes from it as a placeholder, since this is not consistent with the way that a select element would normally work.

test.html

tim1mw avatar Nov 28 '25 11:11 tim1mw

using an empty placeholder (placeholder="") should work too... the idea is that you generally want some kind of placeholder. in many selects, the first option is the one that acts as a placeholder (eg: select an item from the list).

if you don't provide any placeholder or data-placeholder, i guess i could indeed check if the first option has a value instead of assuming it should be removed

lekoala avatar Nov 30 '25 20:11 lekoala

should be fixed

https://github.com/lekoala/bootstrap5-tags/releases/tag/1.7.16

lekoala avatar Nov 30 '25 20:11 lekoala