Checking whether html/css toggle switch has been set to on/off position in go

Hi,

I am trying to implement a toggle switch in my webpage. I’ve followed the site below for doing so:

http://www.w3schools.com/howto/howto_css_switch.asp

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:

func handleSwitch(w http.ResponseWriter, r *http.Request) {
	switchVal := r.FormValue("switch")
	// ...
}

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.

You can also make an AJAX call each time the switch changes instead of submitting a form.

Hey @Chris_S,

Just elaborating on what @nstratos has mentioned, it’s quite simple to just use something like the following for what you are trying to do:

main.go:

package main

import (
	"fmt"
	"html/template"
	"log"
	"net/http"
	"strconv"
)

var tmpl = template.Must(template.New("tmpl").ParseFiles("index.html"))

func indexHandler(w http.ResponseWriter, r *http.Request) {
	if err := tmpl.ExecuteTemplate(w, "index.html", nil); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

func toggleHandler(w http.ResponseWriter, r *http.Request) {
	toggle, err := strconv.ParseBool(r.FormValue("toggle"))
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	if toggle {
		fmt.Fprintln(w, "switch is on")
	} else {
		fmt.Fprintln(w, "switch is off")
	}
}

func main() {
	http.HandleFunc("/", indexHandler)
	http.HandleFunc("/toggle", toggleHandler)
	log.Fatal(http.ListenAndServe(":9000", nil))
}

index.html:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Toggle Switch</title>
		<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
		<script type="text/javascript">
		$(document).ready(function() {
			$("#btn").on("click", function() {
				$.ajax({
					url: "/toggle",
					data: "toggle="+$("#cbox").is(":checked"),
					success: function(data) {
						$("#response").html(data);
					},
				});
			});
		});
		</script>
	</head>
	<body>
		<input id="cbox" type="checkbox">
		<button id="btn">Toggle</button>
		<div id="response"></div>
	</body>
</html>
1 Like

So here is my html code:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
			<title>NMAP Demo</title>
			<link rel="stylesheet" type="text/css" href="layout/css/mystyle.css">
            <link rel="stylesheet" type="text/css" href="layout/css/checkbox.css">
            <link href="https://gitcdn.github.io/bootstrap-toggle/2.2.2/css/bootstrap-toggle.min.css" rel="stylesheet">
            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
                <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
                <script src="https://gitcdn.github.io/bootstrap-toggle/2.2.2/js/bootstrap-toggle.min.js"></script>
				<script type="text/javascript">                                                                                                                                                                                 
                    function myWebsocketStart()   {    
                        console.log("Inside websocket start function")
                        document.getElementById("toggleswitch").submit();                                                                                                                                                             
                        var ws = new WebSocket("ws://localhost:8080/websocket");                                                                                                                                             
                        $('#exec').prop('disabled', true);                                                                                                                                                                                    
                        ws.onmessage = function (evt)                                                                                                                                                                        
                        {  
                            console.log("Inside message function..")
                            var myTextArea = document.getElementById("textarea1"); 
                            var Text = document.getElementById("response");                                                                                                                                           
                            var objMsg = evt.data
                            var HostLen = 0;
                            var HostIp = objMsg.Hosts;
                            var numPorts = 0;

                            console.log($('#toggle-event').prop('checked'))
                            console.log("message received was " + evt.data)    
                            objMsg = JSON.parse(evt.data)

                            if ( objMsg.hasOwnProperty('Value') && objMsg['Value'] != "100%") {
                                document.getElementById("textarea1").innerHTML =  objMsg['Value'] + "%";
                                document.getElementById("response").value="Generating"
                                $('#exec').prop('disabled', true); 
                                $('.progress-bar').css('width', objMsg['Value']+'%').attr('aria-valuenow', objMsg['Value']);
                                                                                                                                                                
                            }  else {
                                document.getElementById("textarea1").innerHTML = "";
                                document.getElementById("response").value = "";
                                if (objMsg.Hosts != null) {
                                    HostLen = objMsg.Hosts.length;
                                }else {
                                    HostLen =0;
                                    document.getElementById("response").value += "No hosts";

                                }
                                for( var i = 0; i < HostLen; i++ ) {
                                    document.getElementById("response").value += "Host " + (i + 1) + "\n";
                                    document.getElementById("response").value += "IP Address: " + objMsg.Hosts[i].Ips[0].Ip + "\n";
                                    document.getElementById("response").value += "Ports: ";
      
                                    if (objMsg.Hosts[i].Ports != null){
                                        console.log(numPorts = objMsg.Hosts[i].Ports.length);
                                    } else {
        
                                        document.getElementById("response").value += "null" +"\n";
                                        document.getElementById("response").value += "\n";
                                        numPorts = 0;
                                    } //should be here, for loop isn't apart of it, whoops
                                  
                                   
                                        for (var j = 0; j < numPorts; j++){
                                            if (j==numPorts-1){
                                                document.getElementById("response").value += objMsg.Hosts[i].Ports[j].Port + "\n"; 
                                                document.getElementById("response").value += "\n";
                                            }else {
                                                document.getElementById("response").value += objMsg.Hosts[i].Ports[j].Port + ", ";

                                            } 
           
                                        }
                                               


 
                                }
                            }
            
                        };                                                                                                                                                                                                                                                                                                                                                                                                                                  
                        ws.onclose = function()                                                                                                                                                                              
                        {                                                                                                                                                                                                    
                            $('#exec').prop('disabled', false);
                            $('.progress-bar').css('width', 0 +'%').attr('aria-valuenow', 0);                                                                                                                                                               
                        };                                                                                                   
                    } //????? should be here, keeps on complaining about this
                                                                                                                                                                               
				</script>
	</head>
	    <body>
       
            <div id ="headerBar">
                <img src="https://www.sandvine.com/images/sv_logos/logo.main.png" />
            </div>
                <div class="jumbotron" id="jumbo">
                    <h2 align="center">PTS Security Demo</h2>
                        <div class="container" id="dothings">
                            <div class="row">
                                  <div class="col-lg-6 col-centered">
                                   <form action="/toggleHandle" method="post" id="toggleswitch" name="toggleswitch"> 
                                    <div class="checkbox">
                                        <label>
                                            <input data-toggle="toggle" type="checkbox" id="toggle-event" name="switch">
                                        </label>
                                    </div>
                                   </form> 
                                      
				                      <div id="buttonformat">
					                      <button onclick="javascript:myWebsocketStart()" id="exec" style="height:75px;width:150px" name="switch"><h3>Execute</h3></button>                                    
				                      </div>
                                      <div class="progress progress-striped active">                                                                                                                                                                   <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="height:60px">
                                           <p id ="textarea1"></p>
                                      </div>                   
                                  </div>
                </div>
                                  <div class="col-lg-6">
                                      <div id="results">
                                          <textarea readonly id="response" rows="20" cols="70" style="resize"></textarea>
                                      </div>
                                  </div>
                            </div>
                        </div>
    </body>
</html>  

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?

Got it working after implementing an ajax call into my javascript function as well. Thanks for the example @radovskyb , that helped a lot.

Oh that’s good. I thought that it might help clear things up for ya :slight_smile:

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.