From b4ac35527eb473ccebd17459945dce2fa2cf6673 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20Stensi=C3=B6?= Date: Mon, 20 Jan 2025 10:41:17 +0100 Subject: [PATCH] Fix 1103 by evaluating hx-vals with `this` referring to the element --- src/htmx.js | 2 +- test/attributes/hx-vals.js | 12 ++++++++++++ www/content/attributes/hx-vals.md | 1 + 3 files changed, 14 insertions(+), 1 deletion(-) diff --git a/src/htmx.js b/src/htmx.js index 424da472c..6a7b2e9e2 100644 --- a/src/htmx.js +++ b/src/htmx.js @@ -3855,7 +3855,7 @@ var htmx = (function() { } let varsValues if (evaluateValue) { - varsValues = maybeEval(elt, function() { return Function('return (' + str + ')')() }, {}) + varsValues = maybeEval(elt, function() { return Function('return (' + str + ')').call(elt) }, {}) } else { varsValues = parseJSON(str) } diff --git a/test/attributes/hx-vals.js b/test/attributes/hx-vals.js index c1f3a1529..aac2b0509 100644 --- a/test/attributes/hx-vals.js +++ b/test/attributes/hx-vals.js @@ -325,4 +325,16 @@ describe('hx-vals attribute', function() { this.server.respond() div.innerHTML.should.equal('Clicked!') }) + + it('js: this refers to the element with the hx-vals attribute', function() { + this.server.respondWith('POST', '/vars', function(xhr) { + var params = getParameters(xhr) + params.i1.should.equal('test') + xhr.respond(200, {}, 'Clicked!') + }) + var div = make('
') + div.click() + this.server.respond() + div.innerHTML.should.equal('Clicked!') + }) }) diff --git a/www/content/attributes/hx-vals.md b/www/content/attributes/hx-vals.md index 20065b47e..3e89bbaea 100644 --- a/www/content/attributes/hx-vals.md +++ b/www/content/attributes/hx-vals.md @@ -43,3 +43,4 @@ In this example, if `foo()` returns an object like `{name: "John", age: 30}`, bo * `hx-vals` is inherited and can be placed on a parent element. * A child declaration of a variable overrides a parent declaration. * Input values with the same name will be overridden by variable declarations. +* When using `javascript:`, `this` refers to the element with the `hx-vals` attribute \ No newline at end of file