Reddirecting to another page with created button

I have this piece of code. If conditions are met i create a button "Show on Map". Now I need to run onclick event on created button that reddirects the user to a map on new URL. I tried with "window.location" in function go_to_map but it doesn't work. Any help?

function coordinates_Conv (d, m, s) {
    return d + m / 60 + s / 3600;
}

function alarm(){
    var lat_d = parseInt(document.getElementsByClassName("lat_deg")[0].value);
    var lat_m = parseInt(document.getElementsByClassName("lat_min")[0].value);
    var lat_s = parseInt(document.getElementsByClassName("lat_sec")[0].value);
    var lon_d = parseInt(document.getElementsByClassName("lon_deg")[0].value);
    var lon_m = parseInt(document.getElementsByClassName("lon_min")[0].value);
    var lon_s = parseInt(document.getElementsByClassName("lon_sec")[0].value);
    if ((coordinates_Conv (lat_d,lat_m,lat_s)<=90) && (coordinates_Conv (lat_d,lat_m,lat_s)>=0) && (coordinates_Conv (lon_d, lon_m, lon_s)<=180) && (coordinates_Conv (lon_d, lon_m, lon_s)>=0)){
    document.getElementById("vypocet").innerHTML= String(Math.round(coordinates_Conv (lat_d,lat_m,lat_s)*1000)/1000) + "<br>" + String(Math.round(coordinates_Conv (lon_d, lon_m, lon_s)*1000)/1000);

    var show_map = document.createElement("button","map");
    show_map.setAttribute("id","map");
    show_map.setAttribute("onclick", go_to_map);
    show_map.innerHTML = "Show on map";
    document.body.appendChild(show_map);

    }
    else {
        alert("Invalid input");
    }
}
function go_to_map(){
    var targetMap = "https://www.mapurl.com/"
    window.location=targetMap;
}

Upvotes: 1

Views: 53

Answers (2)

TimoStaudinger
TimoStaudinger

Reputation: 42480

Your onclick handler never gets called in the first place.

To set it handler correctly, set the element's onclick directly:

show_map.onclick = go_to_map;

Upvotes: 1

Gavin
Gavin

Reputation: 4515

You need to replace show_map.setAttribute("onclick", go_to_map); with show_map.onclick = go_to_map;. This is because onclick is an event and not an attribute.

Upvotes: 0

Related Questions