Search code examples
javascripthrefalpine.js

Problem to concatenate AlpineJS x-text and HREF property


I have a Datatable table being fed by AlpineJS:

<template x-for = "user in users": key = "user.Id">

In x-for, I have the value of user.Id that I can list in a SPAN field, with the instruction x-text:

<span id = "user.Id" class = "text-gray-700 px-6 py-3 flex items-center" x-text = "user.Id"> </span>

I need to concatenate the value of user.Id at the end of my HREF property, which will call a route on the backend to inactivate a record:

Directly, trying to set the HREF + user.Id property, it didn't work, so I thought about the following:

<script>
   var uid = document.getElementById ("user.Id");
   console.log ('uid value:' + uid.InnerText);
   var link = document.getElementById ("link");
   link.setAttribute ('href', 'http://api-paulinhomonteiro-com.umbler.net/cli/delete/<%= token%> /' + uid.innertText)
</script>

It worked very well by setting the property dynamically but the variable arrives as undefined.

How could I solve this? I just discovered AlpineJS and I can't go any further. Can someone help me?


Solution

  • To do this with Alpine you need to use x-bind:

    <span 
      id = "user.Id"
      x-bind:href="'http://api-paulinhomonteiro-com.umbler.net/cli/delete/' + user.Id"
      class = "text-gray-700 px-6 py-3 flex items-center" 
      x-text = "user.Id"> </span>