I am implementing dynamic drop-down selectors using JQuery. I am new to frontend in general. I am struggling to access the value that a dropdown has changed to when I use JQuery.
The user journey is (1) pick a 'collection' and then (2) from within that collection, pick a 'unit'.
I implemented the 'collection' dropdown onchange attribute in HTML like this:
<select name="collection" id="collection" onchange="collectionChanged(this.value)">
With this method, the collectionChanged function gets the value that the dropdown selected has changed to. I then tried to implement the 'unit' onchange behaviour with JQuery. But I get an object that doesn't have a value attribute or anything that looks comparable. I looked at the documentation at the JQuery Website and also at W3CSchools . In both cases, the functions they use do not take any arguments, so I have nothing to compare to. What am I missing?
function getOrCreateUnitSelect() {
let unitSelect;
if ( ! unitSelectExists() ) {
unitSelect = $('<select />', {"id": "unit-select"});
// This is where I add the 'on change' function
unitSelect.change(unitChanged);
unitSelect.insertAfter($('#collection'));
}
else {
unitSelect = $('#unit-select');
}
return unitSelect;
}
function unitSelectExists() {
return $('#unit-select').length;
}
function collectionChanged(value) {
let processFilterResponse = function(serverResponseData, textStatusIgnored, jqXHRIgnored) {
let serverDataObject = JSON.parse(serverResponseData);
let unitSelect = getOrCreateUnitSelect();
serverDataObject['content']['units'].forEach(
function(unit){
$(
"<option />",
{value: unit, text: unit}
).appendTo($("#unit-select"));
}
);
}
let config = {
type: "GET",
url: filterUrl,
data: {'collection': value},
dataType: 'html',
success: processFilterResponse
}
$.ajax(config);
}
function unitChanged(e) {
console.log("unit has been changed");
// Here I get some object that doesn't have a 'value' attribute
console.log(e);
}
When .change
calls a handler, the this
keyword is a reference to the element where the event is being delivered, so in unitChanged(e)
you can just do console.log(this.value)
.
Note: .change(handler)
is just shorthand for .on("change", handler)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.