'How can i bring a variable through a button
I am making a simple shopping website and i wanted to make a loop that created a display for all the items.
<script>
function Test(A) {
alert(A)
}
</script>
<body>
<h1>Hello</h1>
<button on:click = {Test("Hello")}>Test button</button>
</body>
Currently i am running this function and i am getting the alert when loading the website and then the button doesn't do anything. How do i fix this?
Solution 1:[1]
You want this:
<button on:click={() => Test("Hello")}>Test button</button>
By doing on:click={Test("Hello")}, you are saying "call Test when the page loads and add the return value as a click handler on the button." This is why the function is only called once. Instead, you want to pass a reference to a function -- this way, the function is called on each click.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Geoff Rich |
