hi everyone. Is there a way to make a button add 1 to a collection field every time its pressed. example, Button is clicked and the value in the text field increases to 1. when it is pressed again it changes to 2. this is the last thing i need to finish my website. thank you for any advice, It is all appreciated. i have attached a photo of what i am trying to achieve with the collection name and button and text names.
#button10 is pressed and #text52 increases by 1
Thanks
If this number represents total clicks per all users (and not just per a specific user), then you can't add the +1 in the front-end because you'll override other users' clicks.
In that case, you'll have to create a beforeUpdate hook that checks the last stored number and adds +1.
Hey @jakegriffin1990,
See this post for an answer to your question. Regarding the error you received, keep in mind that you are working with both strings (in the text element) and numbers (for incrementing). Assigning a number to a text element will generate an error. You can use the toString() JavaScript function to convert a number to a string.
Tova
import wixData from 'wix-data'; $w.onReady(async function () { const findResult = await findClicks(); let number = findResult.clicks; $w("#text52").text = number.toString(); $w("#button18").onClick(async () => { number += 1; $w("#text52").text = number.toString(); const updateResult = await updateBarbersdatabase(findResult._id, number) }) }); function findClicks() { return wixData.query("Barbersdatabase") .find() .then((res) => { return (res.items[0]) }) } function updateBarbersdatabase(id, number) { wixData.get("Barbersdatabase", id) .then((res) => { res.clicks = number; wixData.update("Barbersdatabase", res) }) }
I am assuming that in the database Barbersdatabase, you only have one item, so findClicks function might be wrong for your case. Also, this code does not limit users to click once, and it might crash if the user clicks it too fast. So in general this code is pretty bad, hope it helps you.
is it like a like button thing? So that you can calculate how many likes you get from different users
thank you for your help. sorry if im doing something simple wrong, But i get this error message
Wix code SDK error: The text parameter that is passed to the text method cannot be set to the value 1. It must be of type string.
this is my code
import wixData from 'wix-data'; export function button18_click(event) { let count = 0; $w('#button18').onClick( ()=> { count++; $w('#text52').text = count; }) }
This is super easy. A good try to learn easy JavaScript ;-)
It can look like this:
let count = 0; // init the variable count $w('#button10').onClick( ()=> { // click on Button or Box (whatever it is) count++; // increment the variable count $w('#text52').text = count.toString(); // give them textField the value of count !and don't forget to cast into a string! })
UPDATE: Added missed ".toString()"