Skip to content

Commit 28fae54

Browse files
MichaelWest221cg
andauthored
Cancel button with inner content form submit properly (#3368)
Co-authored-by: 1cg <[email protected]>
1 parent 032972b commit 28fae54

File tree

2 files changed

+25
-1
lines changed

2 files changed

+25
-1
lines changed

src/htmx.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2430,9 +2430,11 @@ var htmx = (function() {
24302430
if (elt.tagName === 'FORM') {
24312431
return true
24322432
}
2433+
// find button wrapping the event elt
2434+
const btn = elt.closest('input[type="submit"], button')
24332435
// @ts-ignore Do not cancel on buttons that 1) don't have a related form or 2) have a type attribute of 'reset'/'button'.
24342436
// The properties will resolve to undefined for elements that don't define 'type' or 'form', which is fine
2435-
if (elt.form && elt.type === 'submit') {
2437+
if (btn && btn.form && btn.type === 'submit') {
24362438
return true
24372439
}
24382440
elt = elt.closest('a')

test/core/regressions.js

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,4 +363,26 @@ describe('Core htmx Regression Tests', function() {
363363
button.click()
364364
})
365365

366+
it('a htmx enabled button containing sub elements will prevent the button submitting a form', function(done) {
367+
var defaultPrevented = 'unset'
368+
var form = make('<form><button hx-get="/foo"><span>test</span></button></form>')
369+
var button = form.firstChild
370+
var span = button.firstChild
371+
372+
htmx.on(button, 'click', function(evt) {
373+
// we need to wait so the state of the evt is finalized
374+
setTimeout(() => {
375+
defaultPrevented = evt.defaultPrevented
376+
try {
377+
defaultPrevented.should.equal(true)
378+
done()
379+
} catch (err) {
380+
done(err)
381+
}
382+
}, 0)
383+
})
384+
385+
span.click()
386+
})
387+
366388
})

0 commit comments

Comments
 (0)