How to use the result of a javascript function as a phx-value for phx-click

Hello everyone,

I am trying to use phx-click on a button and I am handling the event on the server (no problem here).

If I do this, everything works fine.

 <button phx-click="save" phx-value-number="<%= floor.number %>">
        <i class="fas fa-save"></i>

But I would like to add a second value, so when I click on save the js function is executed and I can send the return of the function as a param.

 <button phx-click="save" phx-value-number="<%= floor.number %>" phx-value-newParam="doSomethingInJs('<%= floor.number %>');">
        <i class="fas fa-save"></i>

What is the easiest way to do something like this?

Thank you for your help.

I don’t think that is possible as JS doesn’t know to do something in that tag.

you could try phx-value-newParam="javascript:doSomethingInJs('<%= floor.number %>');"

but I highly doubt browser will execute that.

You can try setting the calculation from a function via dom yourself?

document.getElementById('specialButton').attr('phx-value-newParam', doSomething('<%= value %>'))

ps: that is a pseudo-code…

maybe look into even listeners and hooks? seems like that is gonna be useful in your case rather than the hacky code I just proposed

Thank you I got it working by using Hooks and a ‘normal’ js onclick.

That’s what I didn’t understand : that if you use Hooks you don’t use phx-click but just add the pushEvent in the normal js onclick handler.

Thamk you for your help.

Glad you got it worked out!

phx-click is the convenience hook shortcut. It does exactly what you did, calls pushEvent with the phx-values

OK so to summarize :
- if the values I want to send are already available with no modifications, just send them with phx-click and phx-value-xxx
- if (like I needed to do in my example) the values need some kind of pre-processing, remove the phx-click, use a standard onclick and process the values in the hook before sending the pushEvent

Indeed I didn’t have to change anything in the server to handle the event so this is great IMO :slight_smile: