I currently have my html file set up with a button and this toggle switch. I also configured my webserver in go to be listening on localhost:8080. And I have a websocket handler configured, so that I can easily pass data through to my webpage on the click of the button.
What I want to do create a toggle switch on my webpage that the user can switch on and off, and then have them click a button. After that button is clicked I want to analyse the users selection using an if condition in my golang code based on whether this toggle switch is on/off, but I cannot figure out how to access this value in go. Any suggestions would be helpful. Also, it’d be ideal to have a toggle switch implemented, but if anyone has any simpler ideas for this use case then I’d be open to them.
The switch is just an <input type="checkbox"> made fancy with CSS. All you have to do to get its value is to add a name attribute and the value will get to the server when you submit the form (or manually send an AJAX request).
So in your HTML it is going to be something like this <input type="checkbox" name="switch"> and in your Go handler something like this:
Thanks for the response, but the problem is if I wrap a form around my checkbox, then I wouldn’t I have to add the attributes method=“post”, action="/something" after submitting my form? Also, this would redirect me to an endpoint my webpage is not rendering on. So how would I be able to submit this form without this redirection happening? And if I cannot stop this redirect how can I work around this. My webpage is currently rendering on “/” endpoint.
What i tried doing was creating a form wrapped around my checkbox, and then executing a form submit in javascript when the button in my webpage is pressed. I created a handler in go to handle this. In my toggleHandle function in go, I’m simply doing r.ParseForm() and fmt.Println(r.Form). This prints the value of the switch when run my web application, but also changes the endpoint of the page I am rendering my page on. Currently I am using websockets to relay the output of a terminal command executed in go, over to javascript to be printed to a textarea in realtime on the click of a button. What I want to implement is a switch I can flip on/off and execute a command in go according to the switches position. I’m not overly familiar with ajax, but would this work if i incorporated the above example into my html file, having websockets and ajax in javascript?