Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use javascript in hx:vals #160

Open
engnaruto opened this issue Dec 25, 2024 · 2 comments
Open

Use javascript in hx:vals #160

engnaruto opened this issue Dec 25, 2024 · 2 comments

Comments

@engnaruto
Copy link

engnaruto commented Dec 25, 2024

Hi, is there a way to use javascript in hx:vals?

I need to do something like this:

 hx:vals="${ {stageIndex: stageIndex, stepCount: document.querySelectorAll('.taskStep').length} }"

so my use case is to create a json using thymeleaf variables and using javascript at the same time

when I try this, I get this exception:

[nio-8080-exec-8] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/partials/....html]")] with root cause


org.springframework.expression.spel.SpelEvaluationException: EL1011E: Method call: Attempted to call method querySelectorAll(java.lang.String) on null context object
@checketts
Copy link
Collaborator

Can you include what you would expect the rendered HTML to look like? I'm having trouble understanding the request.

I typically would solve something like this as a hidden field and avoid the Javascript approach:

<input type="hidden" name="stepCount" th:value="${steps.size}">

@engnaruto
Copy link
Author

engnaruto commented Dec 27, 2024

Thanks @checketts. I wanted to send these information to the Spring controller so based on it I can determine the properties of new fragment that I wanted to render.

After doing some search, I found that I can use the javascript event to get what I need:

hx-vals='js:{stageIndex: event.target.closest(".taskStage").getAttribute("stageIndex"), stepCount: event.target.closest(".taskStage").querySelectorAll(".taskStep").length}'

maybe there is a better solution for this in thymeleaf that I am not aware of it as this is the first project to use thymeleaf and htmx

what I am working on is a form that adds new empty input fields (stages and steps of the stages) when I click add stage or add step in a stage, so I don't want to make the button to submit the whole form when I click it, so I use htmx to send a request to the spring boot controller with the values needed so the controller returns a fragment with the correct input attributes

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants
@checketts @engnaruto and others