Repeaters and actions

I wand to add a button to a repeater and run something when the button is pressed.

Lets say we have a repeater with products, if the user clicks add to cart then I get the information of the clicked item and do something with it.

2 Likes

Hi!

What is the question?
What are you trying to achieve?

Doron.

Carlos:
You can take the same approach as you would using a button that is not on a repeater. The difference that you need to pay attention to is the scope used by the repeater.

So as an example:

If you have a button and a textBox on a regular page you can either create an event handler in the $w.onReady() function like so:

$w.onReady(() => {
        $w('#button').onClick(clickHandler);
}

function clickHandler(event, $w) {
    console.log($w('#textBox').value);
}

or you can connect the event handler to the element in the element property dialogue like so:

Now you can do exactly the same thing with a repeater. The trick with a repeater (which should be transparent to you but worth understanding) is that where $w in the handler we talk about above means ā€œelements on this pageā€. The $w in the event handler for an element in a repeater means ā€œelements in this repeater item instanceā€.

So if you read this documentation (https://www.wix.com/code/reference/$w.Repeater.html) you will see how the scope is used.


So in your example if you have a button called $w(ā€˜#addToCartā€™) and you have a handler attached to that button

        $w('#addToCart').onClick(addItemToCart);

Then your handler function can assume that the repeater element that you have, letā€™s call it product, can be accessed as follows:

let shoppingCart = []; // Empty array of items
$w.onReady( function () {
    $w('#addToCart').onClick(addItemToCart);
}

function addItemToCart(event, $w) {
    let productSelected = $w('#product').value;
    // Use console.log to help debugging
    console.log(productSelected); // Assume #product is a text name
    shoppingCart.push(productSelected);
}

Hope that helps.

@doron-alkalay
Basically if a button is inside repeater and you write a onClick() function for it, then all buttons in repeater elements acts same and programmatically you canā€™t distinguish between buttons , since all buttons will have same label

@stcroppe answered it in details and very clear. I donā€™t know why Wix is not allowing me to upvote his answer.

For people who need short answer,
In event handler function, you just add $w as second parameter, everything else will sort out by itself.
// button is inside a repeater
Eg: export function button_click ( event , $w ) {
//function code here
}

Thank you for simplifying this.