I was under the impression that I could get the value of a select input by doing this $(this).val();
and applying the onchange
parameter to the sel
Let me share an example which I developed with BS4, thymeleaf and Spring boot.
I am using two SELECTs, where the second ("subtopic") gets filled by an AJAX call based on the selection of the first("topic").
First, the thymeleaf snippet:
select
select
Errors
I am iterating over a list of topics that is stored in the model context, showing all groups with their topics, and after that all topics that do not have a group. BaseIdentity is an @Embedded composite key BTW.
Now, here's the jQuery that handles changes:
$('#topicId').change(function () {
selectedOption = $(this).val();
if (selectedOption === "") {
$('#subtopicsId').prop('disabled', 'disabled').val('');
$("#subtopicsId option").slice(1).remove(); // keep first
} else {
$('#subtopicsId').prop('disabled', false)
var orig = $(location).attr('origin');
var url = orig + "/getsubtopics/" + selectedOption;
$.ajax({
url: url,
success: function (response) {
var len = response.length;
$("#subtopicsId option[value!='']").remove(); // keep first
for (var i = 0; i < len; i++) {
var id = response[i]['baseIdentity']['id'];
var name = response[i]['name'];
$("#subtopicsId").append("");
}
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
}).change(); // and call it once defined
The initial call of change() makes sure it will be executed on page re-load or if a value has been preselected by some initialization in the backend.
BTW: I am using "manual" form validation (see "is-valid"/"is-invalid"), because I (and users) didn't like that BS4 marks non-required empty fields as green. But that's byond scope of this Q and if you are interested then I can post it also.