Reputation: 25
I would like disable this submit button if the text entered in this input is not in datalist
.
<label><h5>Code application</h5></label>
<input
name="applicationCodeId"
id="applicationCodeId"
list="applicationCodeList"
class="disableAutoComplete"
/>
<datalist id="applicationCodeList">
<div th:each="applicationCode : ${applicationCodes}">
<option
name="applicationCodeId"
th:text="${applicationCode.applicationCodeName}+ ' : ' +${applicationCode.projectName}"
th:value="${applicationCode.getId()}"
></option>
</div>
</datalist>
Upvotes: 1
Views: 1157
Reputation: 15976
You can rely on the disabled
attribute of your submit button/input: update it every time the input content is modified. An option is to use querySelector
to check if the current text match an option value with the selector option[value="..."]
. Something like that:
function myFunction() {
const currentValue = document.getElementById('applicationCodeId').value;
document.getElementById("mySubmit").disabled =
currentValue.length === 0 ||
document.querySelector('option[value="' + currentValue + '"]') === null;
}
<label><h5>Code application</h5></label>
<input
name="applicationCodeId"
id="applicationCodeId"
list="applicationCodeList"
class="disableAutoComplete"
oninput="myFunction()"
/>
<datalist id="applicationCodeList">
<option value="Option 1">
<option value="Option 2">
</datalist>
<input type="submit" id="mySubmit" disabled>
Be aware that when using <datalist>
, the option value takes precedence on the text: you may type the text inside the input, but it will be replaced with the value. That's why the above solution is based on values :)
Note that a datalist should only contains <option>
elements: no <div>
(see documentation). The names can also be removed on the options.
Because the solution above works on the value attribute, your code may become:
<datalist id="applicationCodeList">
<option
th:each="applicationCode : ${applicationCodes}"
th:value="${applicationCode.applicationCodeName}+ ' : ' +${applicationCode.projectName}"
>
</datalist>
You will have to retrieve the id in server side ;)
Upvotes: 2