Connect button to text and url field with Javascript

I am trying to connect some buttons to 2 fields in the database by using Javascript.

I need to connect the button text to a text field, and the URL destination to a URL field, whilst opening the URL in a new window.

I know this can easily be done by connecting the button via a dataset, but would prefer it all to be done via Javascript if possible.

Thanks

Hi,

From my understanding, it seems you are trying to set links to repeated buttons within a Repeater. You can accomplish this without a dataset by manually querying the relevant collection and setting up the repeater using .data and .onItemReady().

Example Code

import wixData from 'wix-data';

$w.onReady(function () {
    
    //Queries the collection with the text and url fields needed for the buttons
    wixData.query("Collection").find()
        .then((results) => {
            $w('#repeater').data = results.items; //Sets repeater data to the data queried from the collection
        })

    $w('#repeater').onItemReady(($item, itemData, index) => {
        $item('#repeatedButton').label = itemData.title; //Sets Button Label to Text Field (.title should change to your text field name)
        $item('#repeatedButton').link = itemData.url; //Sets Button Link to URL Field (.link should change to your url field name)
    });

});

Hi
These are not buttons in a repeater, these are individual buttons, how would this work with the coding for these?

Thanks

If that is the case you can manually set the button label and links using the Button Element properties after querying your collection.

import wixData from 'wix-data';

$w.onReady(function () {

    //Queries the collection with the text and url fields needed for the buttons
    wixData.query("Collection").find()
        .then((results) => {
            const items = results.items;

            //Use result.items object to manually set the label and link for each Button Element. 
            //Example (Add additional buttons as required):
            $w('#button1').label = items[0].title; //Sets Button Label to Text Field (.title should change to your text field name)
            $w('#button1').link = items[0].url; //Sets Button Link to URL Field (.link should change to your url field name)

        });

});
1 Like

Works, thank you so much :+1:

1 Like