I am trying to assign 2 different javascript variable values from multiple data-attributions in a dropdown menu. One value is working just fine, the other keeps returning null. Any suggestions would be greatly appreciated!
Example of an option line from html form:
<select onchange="calculateNPF()" id="yourCamera" name="yourCamera" class="form-control">
<option value="79" data-sensor-width="36" data-sensor-height="24" data-cropFactor="1" data-pixelPitch="6.6" data-resolution="20.1">Canon EOS R6</option>
let yourCameraPixelSize = document.getElementById('yourCamera');
let pixelSize = yourCameraPixelSize.getAttribute('data-pixelPitch');
let yourCameraSensorSize = document.getElementById('yourCamera');
let sensorSize = yourCameraSensorSize.getAttribute('data-cropFactor');
In the above code "pixelSize" is working properly whereas sensorSize returns null
You're trying to get the attribute values from the select
element, but they're on the option
element.
If you're trying to get these attribute values from the selected option (or options), you can use the selectedOptions
collection for that. Since it's a single-select, you'd just want .selectedOptions[0]
for the first (only) one. Here's an example:
function calculateNPF() {
const yourCamera = document.getElementById("yourCamera");
const selectedOption = yourCamera.selectedOptions[0];
if (!selectedOption) {
return;
}
const yourCameraPixelSize = selectedOption.getAttribute('data-pixelPitch');
const yourCameraSensorSize = selectedOption.getAttribute('data-cropFactor');
console.log(`yourCameraPixelSize = ${yourCameraPixelSize}`);
console.log(`yourCameraSensorSize = ${yourCameraSensorSize}`);
}
<select onchange="calculateNPF()" id="yourCamera" name="yourCamera" class="form-control">
<option>Choose an option</option>
<option value="79" data-sensor-width="36" data-sensor-height="24" data-cropFactor="1" data-pixelPitch="6.6" data-resolution="20.1">Canon EOS R6</option>
</select>
I should note that the name yourCameraSensorSize
doesn't really match the attribute name data-cropFactor
though.
FWIW, I suggest avoiding onxyz
-attribute-style event handlers and using addEventListener
instead. You could also use the dataset
property if you like. Here that is with your original attribute and variable names:
const yourCamera = document.getElementById("yourCamera");
yourCamera.addEventListener("change", calculateNPF);
function calculateNPF() {
const selectedOption = yourCamera.selectedOptions[0];
if (!selectedOption) {
return;
}
const {
pixelpitch: yourCameraPixelSize,
cropfactor: yourCameraSensorSize
} = selectedOption.dataset;
console.log(`yourCameraPixelSize = ${yourCameraPixelSize}`);
console.log(`yourCameraSensorSize = ${yourCameraSensorSize}`);
}
<select id="yourCamera" name="yourCamera" class="form-control">
<option>Choose an option</option>
<option value="79" data-sensor-width="36" data-sensor-height="24" data-cropFactor="1" data-pixelPitch="6.6" data-resolution="20.1">Canon EOS R6</option>
</select>