Skip to content

Commit 37f2e96

Browse files
authored
Merge pull request #415 from Codeinwp/fix/select-images-required
fix: image selection for Image Input
2 parents b55dca4 + 37efca5 commit 37f2e96

File tree

1 file changed

+28
-29
lines changed

1 file changed

+28
-29
lines changed

js/ppom.inputs.js

Lines changed: 28 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -174,38 +174,37 @@ function ppom_init_js_for_ppom_fields(ppom_fields) {
174174
*/
175175
const selectedImgs = [];
176176

177-
container.querySelectorAll('.pre_upload_image').forEach( (/** @type{HTMLDivElement} */ inputContainer) => {
178-
const input = inputContainer.querySelector('input');
179-
if ( ! input ) {
180-
return;
181-
}
182-
183-
const multiple = input.dataset.allowMultiple || false;
184-
if ( multiple ) {
185-
if (input.dataset.required) {
186-
input.checked = true;
177+
/**
178+
* @type {HTMLInputElement[]} The available images to select.
179+
*/
180+
const imgsInput = Array.from(container.querySelectorAll('.ppom-input.pre_upload_image input'));
181+
182+
for ( const imgInput of imgsInput ) {
183+
const multiple = imgInput.dataset.allowMultiple || false;
184+
const maxImgSelection = parseInt( imgInput.dataset?.maxSelection ?? '-1' );
185+
186+
imgInput.addEventListener('click', (e) => {
187+
if ( !e.target.checked ) {
188+
return;
187189
}
188-
189-
const siblings = Array.from(input.parentNode.parentNode.querySelectorAll('input.ppom-input.image'));
190-
siblings.filter(sibling => sibling !== input).forEach(sibling => sibling.checked = false);
191-
} else {
192-
const maxImgSelection = parseInt( input.dataset?.maxSelection ?? '1' );
193-
if ( maxImgSelection ) {
194-
inputContainer.querySelector('img')?.addEventListener( 'click', () => {
195-
selectedImgs.push( input );
196-
197-
while( selectedImgs.length > maxImgSelection ) {
198-
const oldestImgSelected = selectedImgs.shift();
199-
if ( oldestImgSelected ) {
200-
oldestImgSelected.checked = false;
201-
}
202-
}
203-
})
204190

191+
if ( ! multiple ) {
192+
// Uncheck other inputs.
193+
imgsInput.filter( i => i !== imgInput).forEach( i => {
194+
i.checked = false;
195+
});
196+
} else if ( 0 < maxImgSelection ) {
197+
// Uncheck oldest checked image.
198+
selectedImgs.push( imgInput );
199+
while( selectedImgs.length > maxImgSelection ) {
200+
const oldestImgSelected = selectedImgs.shift();
201+
if ( oldestImgSelected ) {
202+
oldestImgSelected.checked = false;
203+
}
204+
}
205205
}
206-
}
207-
208-
});
206+
});
207+
}
209208
});
210209

211210
// Data Tooltip

0 commit comments

Comments
 (0)