Currently working on an AJAX form where users can choose a background color or upload a background image. The aim is to have the bgColor field ignored if a file is specified for bgImg.
<label>Color: <input type="color" name="bgColor" value="#000000"></label><br>
<label>Image: <input type="file" name="bgImg" accept="image/png"></label><br>
I thought using the FormData API would be the simplest way to collect the form data:
var fd = new FormData(document.getElementById('myForm'));
The issue arises when trying to determine if a file has been selected in the FormData object. When checking fd.has('bgImg')
, it returns true regardless of whether a file is actually selected, which makes sense because the field exists.
However, when attempting to check with fd.get('bgImg')
, my browser crashes if no file is selected. This creates a situation where determining if the bgImg field is empty becomes impossible. So, what is the correct approach in this case?
While I could use elements['bgImg'].files from the form, I prefer sticking to the FormData API for its simplicity and cleanliness. Is there a reason why it seems to malfunction in this scenario? Is checking the files collection the only viable solution?
UPDATE: It appears that the FormData API may not have strong browser support outside of Firefox, so relying on element.files might be a more reliable option. However, the unexpected crashing in Firefox remains a mystery. If no explanation is found soon, I might provide my own solution.