I have a multiple select where each option has a class set to it. Depending on the class i can pre-select all options with a specific class so the user doesn't have to select them all by himself. So far it works fine, till to the point where i manually select one option by clicking on it. From this point on the pre-selects seem to don't work anymore. BUT only the visuals don't work anymore, the options still get the 'selected="selected"' applied to them. Also .val() on the select returns all values selected by the pre-selector. So in the background everything works fine, but the user can't see that it worked.
Here's my select:
<select class="form-control d-block w-100 col-8 col-xl-12" id="brand-select" name="brands" size="15" multiple>
<c:forEach var="brand" items="${brands}">
<option class='<c:choose>
<c:when test="${brand.isCompanyBrand()}">COMPANYBRAND</c:when>
<c:otherwise>FOREIGNBRAND</c:otherwise>
</c:choose>' value="${brand.brandCode}">${brand.description}
</option>
</c:forEach>
</select>
And here's one of the selectors:
selectCompanyBrands.addEventListener("click", function()
{
$("#brand-select option").attr("selected", false)
$("#brand-select option.COMPANYBRAND").attr("selected", true);
}, false);
I'm currently out of ideas what i can do to resolve this problem.
Here is a sample working code to help you. I have used
prop()
:Read through this in jquery
doc
and I quote for specificity:Jquery, or rather its later versions, clearly distinguishes between attributes and properties. So the simple rule is that if you want to set a property (something that is related to a user action like a form element) use
#prop()
and otherwise use#attr()
.Here you should be using
#prop
like this: