skip to Main Content

I am working on an astronomical application that determines the location of the sun and the resulting shadow lengths and shadow azimuths at different times of the day. I want to eventually deploy this on a mobile phone and as such I am employing the HTML Geolocation API to obtain the latitude and longitude of the device and the time at which the location was requested. With that information I compute the position of the sun and the parameters that I am interested in in a fuction called soalrTimeDetails, which I have tested extensively for correct results – it is not the problem.

I also want to have the ability to choose the location (latitude, longitude, and Date) manually for future or past solar reuslts, and so I also have a form that gives the user the option to determine location and date automatically (the default) or manually via a radio button. The form also has a date picker section where the date can be obtained automatically (the default) or manually. The form also has some additional radio buttons to pick what solar conditions I am seeking. The form works fine as well. Until I click on one of three buttons.

I have a "Save", "Update", and "Reset" buttons. The Reset button works perfectly fine, resetting the form to the defaults. The Save and Update buttons call a function chooseMethod(this.form) that is supposed to store the form data in localStorage and then determine if location and date are to be obtained automatically or manually and then once obtained, calls the solarTimeDetails() function.

Here is my problem. When I initally load the page, it will obtain location and date automatically and display the reuslts. But if I then try to enter the form parameters manually, it runs as it should, but then reloads and runs automatically. I cannot figure out how to keep it from running automatically once I click on either the Save or Update buttons.

Here is the portion of my application that is pertinent to this problem

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://use.typekit.net/ihb7rrh.css">  
<link rel="stylesheet" href="shadows_test3.css" />
<title>Shadows Test 3</title>
<script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous">
//$(document).ready(function(){window.onload = dataLoad();});
    

</script>
<title>Sun Tracker</title>
</head>

<body onload="getLocation()">
    
    <form id="settingsInput" class="dropdown contents" autocomplete="on">
        <fieldset class="locfield">
            <legend>Location<br></legend>
            <input type="radio" name="location" value="auto" id="autoloc" checked><label for="autoloc"> Auto</label><br><hr class="settingsDivider">
            <input type="radio" name="location" value="manual" id="manualloc"><label for="manualloc"> Manual</label><br>
                    Latitude:<br> <input type="number" name="latitude" maxlength="10" class="locinput" style="width:6em"><br>
                    <input type="radio" name="NS" value="north" id="North"><label for="North"> North</label><br>
                    <input type="radio" name="NS" value="south" id="South"><label for="South"> South</label><br>
                    Longitude:<br> <input type="number" name="longitude" class="locinput" style="width:6em"><br>
                    <input type="radio" name="EW" value="east" id="East"><label for="East"> East</label><br>
                    <input type="radio" name="EW" value="west" id="West"><label for="West"> West</label><br>
                    Elevation:<br> <input type="number" name="landelev" class="locinput" style="width:6em"><br>
                    <input type="radio" name="elevunits" value="feet" id="feet"><label for="feet"> Feet</label><br>
                    <input type="radio" name="elevunits" value="meters" id="meters"><label for="meters"> Meters</label><br>
                    Time Zone:<br> <select name="timezones">
                        <option value="-12">UTC-12</option>
                        <option value="-11">UTC-11</option>
                        <option value="-10">UTC-10</option>
                        <option value="-9">UTC-9</option>
                        <option value="-8">UTC-8</option>
                        <option value="-7">UTC-7</option>
                        <option value="-6">UTC-6</option>
                        <option value="-5">UTC-5</option>
                        <option value="-4">UTC-4</option>
                        <option value="-3">UTC-3</option>
                        <option value="-2">UTC-2</option>
                        <option value="-1">UTC-1</option>
                        <option value="0">UTC+0</option>
                        <option value="1">UTC+1</option>
                        <option value="2">UTC+2</option>
                        <option value="3">UTC+3</option>
                        <option value="4">UTC+4</option>
                        <option value="5">UTC+5</option>
                        <option value="6">UTC+6</option>
                        <option value="7">UTC+7</option>
                        <option value="8">UTC+8</option>
                        <option value="9">UTC+9</option>
                        <option value="10">UTC+10</option>
                        <option value="11">UTC+11</option>
                        <option value="12">UTC+12</option>
                    </select><br>
            <span><label for="Manualdst" style="font-size:15px">Daylight Saving?</label></span><br>
            <input type="checkbox" name="ManualDST" value="DST" id="Manualdst">
        </fieldset>
            
        <fieldset class="datefield">
            <legend>Date</legend>
            <input type="radio" name="dateMode" value="auto" id="autodate" checked><label for="autodate"> Auto</label><br><hr class="settingsDivider">
            <input type="radio" name="dateMode" value="manual" id="manualdate"><label for="manualdate"> Manual</label><br>
            Select Date:<br>
            <input type="date" name="dateInput" class="dateinput" style="width:6em"><br><hr class="settingsDivider">
        </fieldset>
        <fieldset class="eventfield">
            <legend>Events</legend>
                    <!--<span style="text-decoration: underline">Subh Cond:</span><br>-->
                    <span>Astro Cond:</span><br>
                    <input type="radio" name="astroMode" value="12" id="astrourban" checked><span><label for="astrourban"> Urban</label></span><br>
                    <input type="radio" name="astroMode" value="15" id="astrowild"><span style="font-size: 17px"><label for="astrowild"> Wilderness</label></span><br><hr class="settingsDivider">
                    <span class="noontext">Noon Shadow:</span><br>
                    <input type="radio" name="noonMode" value="42" id="noonsandal"><span style="font-size: 15px"><label for="noonsandal"> Sandal Strap</label></span><br>
                    <input type="radio" name="noonMode" value="21" id="noonhand" checked><span style="font-size: 17px"><label for="noonhand"> Hand Span</label></span><br>
                    <input type="radio" name="noonMode" value="7" id="noonfoot"><span style="font-size: 17px"><label for="noonfoot"> Foot Span</label></span><br><hr class="settingsDivider">
                    <!--<span style="text-decoration: underline">Asr Shadow:</span><br>-->
                    <span>Afternoon Shadow:</span><br>
                    <input type="radio" name="afternoonMode" value="1" id="afternoonmajority" checked><span style="font-size: 20px"><label for="afternoonmajority"> Majority</label></span><br>
                    <input type="radio" name="afternoonMode" value="2" id="afternoonlong"><span><label for="afternoonlong"> Long</label></span><br><hr class="settingsDivider">
                    <!--<span style="text-decoration: underline">Isha Cond:</span><br>-->
                    <span>Night Cond:</span><br>
                    <input type="radio" name="nightMode" value="12" id="nighturban"><span><label for="nighturban"> Urban</label></span><br>
                    <input type="radio" name="nightMode" value="15" id="nightwild" checked><span style="font-size: 17px"><label for="nightwild"> Wilderness</label></span><br>
        </fieldset>
        <div class="set-section">
            <button name="solartimes" value=" Save " onclick="chooseMethod(this.form)">Save</button>
        </div>
        <div class="update-section">
            <button name="updatesolartimes" value=" Update " onclick="chooseMethod(this.form)">Update</button>
        </div>
        <div class="reset-section">
            <button type="reset" value=" Reset ">Reset</button>
        </div>
    </form>
    <div>
        <!--shows date and location-->
    </div>
    <div>
        <!--shows events and times when they occur-->
    </div>
    <div>
        <!--shows graphic of solar azimuth-->
    </div>
    <div>
        <!--shows graphic of soalr altitude-->
    </div>
    
    <script>
        function getLocation() {
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(savePosition);
            } else { 
                x.innerHTML = "Geolocation is not supported by this browser.";
            }
        } //end of getLocation()

        function savePosition(position) {
            var latitude = position.coords.latitude.toFixed(4).valueOf();
            var longitude = (position.coords.longitude.toFixed(4) * -1.0).valueOf();
            var locElev = (position.coords.altitude * 3.2808).toFixed(0).valueOf();
            var currentDate = new Date(position.timestamp);
            var currentMinutes = Number(currentDate.getHours()) * 60 + Number(currentDate.getMinutes());
            
            if(localStorage.getItem("settingsObject") !== null)
            {
                var inputParse = JSON.parse(localStorage.getItem("settingsObject"));
            }
            
            if (typeof(Storage) !== "undefined")
            {
                var formData = CacheData();
            }
            else
            {
                document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
            }
            
                
            var sDelta = Number(inputParse.astroMode);
            var dDelta = Number(inputParse.noonMode);
            var aDelta = Number(inputParse.afternoonMode);
            var iDelta = Number(inputParse.nightMode);
            var dateCheck = inputParse.dateMode;
            alert("in savePosition");
            alert(sDelta);
            alert(dDelta);
            alert(aDelta);
            alert(iDelta);
            alert(dateCheck);
            
            document.getElementById("data25").innerHTML = latitude;
            document.getElementById("data26").innerHTML = longitude;
            document.getElementById("data28").innerHTML = locElev;
            
            if (latitude > 0)
            {
                var NSlat = "N";
            }
            else if (latitude < 0)
            {
                NSlat = "S";
            }
            else
            {
                NSlat = "EQ"
            }
            
            if (longitude < 0)
            {
                var EWlong = "E";
            }
            else if (longitude > 0)
            {
                EWlong = "W";
            }
            else
            {
                EWlong = "PM"
            }
            document.getElementById("data36").innerHTML = NSlat;
            document.getElementById("data37").innerHTML = EWlong;
            
            if (dateCheck == "auto")
            {
                var dateData = new Date();

                year = dateData.getFullYear();
                month = dateData.getMonth() + 1;
                day = dateData.getDate();

                var zoneMinutes = dateData.getTimezoneOffset();
                var timezone = zoneMinutes / 60;
                timezone = -1.0 * timezone;
                alert(currentMinutes);
            }
            else if (dateCheck == "manual")
            {
                alert(inputParse.dateInput);
                var dateData = new Date(inputParse.dateInput);
                dateData = new Date(
                    dateData.getUTCFullYear(),
                    dateData.getUTCMonth(),
                    dateData.getUTCDate(),
                    dateData.getUTCHours(),
                    dateData.getUTCMinutes(),
                    dateData.getUTCSeconds(),
                    dateData.getUTCMilliseconds());
                alert(dateData);
                year = dateData.getFullYear();
                //month = dateData.getMonth() + 1;
                //day = dateData.getDate() + 1;
                alert(currentMinutes);

                if (month == 10 || month == 8 || month == 7 || month == 5 || month == 3 || month == 1)
                {
                    if (day > 31)
                    {
                        month = month + 1;
                        day = 1;
                    }
                }
                if (month == 12)
                {
                    if (day > 31)
                    {
                        month = 1;
                        day = 1;
                    }
                }
                if (month == 11 || month == 9 || month == 6 || month == 4)
                {
                    if (day > 30)
                    {
                        month = month + 1;
                        day = 1;
                    }
                }
                if (month == 2)
                {
                    if (isLeapYear(year))
                    {
                        if (day > 29)
                        {
                            month = 3;
                            day = 1;
                        }
                    }
                    else
                    {
                        if (day > 28)
                        {
                            month = 3;
                            day = 1;
                        }
                    }
                }

                
                var timezoneIndex;
                var daylightSaving;
                var timezone = 0;
                
                var zoneMinutes = dateData.getTimezoneOffset();
                var zone = zoneMinutes / 60;
                var timezone = -1.0 * zone;
            }
            
            document.getElementById("data27y").innerHTML = year;
            document.getElementById("data27m").innerHTML = month;
            document.getElementById("data27d").innerHTML = day;
            
            solarTimeDetails = calcSolarTimes(latitude, longitude, locElev, day, month, year, timezone, dDelta, aDelta, sDelta, iDelta);
            
            document.getElementById("data35").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[35]));
            document.getElementById("data3").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[2]));
            document.getElementById("data4").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[3]));
            document.getElementById("data6").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[5]));
            document.getElementById("data12").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[11]));
            document.getElementById("data16").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[15]));
            document.getElementById("data20").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[19]));
            document.getElementById("data21").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[20]));
            
            localStorage.setItem("elevation", solarTimeDetails[36]);
            localStorage.setItem("shadowAzimuth", solarTimeDetails[37]);
            localStorage.setItem("latitude", latitude);
            localStorage.setItem("longitude", longitude);
            localStorage.setItem("currentTime", currentMinutes);
            
            localStorage.setItem("astroTime", timeToMinutes(solarTimeDetails[3]));
            localStorage.setItem("sunriseTime", timeToMinutes(solarTimeDetails[5]));
            localStorage.setItem("noonTime", timeToMinutes(solarTimeDetails[11]));
            localStorage.setItem("afternoonTime", timeToMinutes(solarTimeDetails[15]));
            localStorage.setItem("sunsetTime", timeToMinutes(solarTimeDetails[19]));
            localStorage.setItem("nightTime", timeToMinutes(solarTimeDetails[20]));
            localStorage.setItem("morningTime", timeToMinutes(solarTimeDetails[39]));
            
            localStorage.setItem("transitTime", solarTimeDetails[38]);
            
            
            localStorage.setItem("transitElev", solarTimeDetails[40]);
            localStorage.setItem("currentMinutes", currentMinutes);
            var SunAltitude = [];
            SunAltitude = localStorage.getItem("elevation").split(",");
            document.getElementById("currentAlt").innerHTML = Number(SunAltitude[currentMinutes]).toFixed(1);
            
            
            alert("end savePosition");
        }
        
        function chooseMethod(form)
        {
            alert("in chooseMethod");
            var timezoneIndex;
            var daylightSaving;
            var timezone = 0;
            
            if(localStorage.getItem("settingsObject") !== null)
            {
                var inputParse = JSON.parse(localStorage.getItem("settingsObject"));
            }
            if (typeof(Storage) !== "undefined")
            {
                var formData = CacheData();
            }
            else
            {
                document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
            }
            
            var coordinates = "";
            for (i = 0; i < 3; i++)
            {
                if (form.location[i].checked)
                {
                    coordinates = form.location[i].value;
                }
            }
            var dateCheck = "";
            for (i = 0; i < 2; i++)
            {
                if (form.dateMode[i].checked)
                {
                    dateCheck = form.dateMode[i].value;
                }
            }
            
            var dDelta;
            for (i = 0; i < 3; i++)
            {
                if (form.dhuhurMode[i].checked)
                {
                    dDelta = Number(form.dhuhurMode[i].value);
                }
            }

            var aDelta;
            for (i = 0; i < 2; i++)
            {
                if (form.asrMode[i].checked)
                {
                    aDelta = Number(form.asrMode[i].value);
                }
            }

            var sDelta;
            for (i = 0; i < 2; i++)
            {
                if (form.subhMode[i].checked)
                {
                    sDelta = Number(form.subhMode[i].value);
                }
            }

            var iDelta;
            for (i = 0; i < 2; i++)
            {
                if (form.ishaMode[i].checked)
                {
                    iDelta = Number(form.ishaMode[i].value);
                }
            }
            
            if(coordinates == "auto")
            {   
                alert("chooseMethod auto going into geoLocation");
                getLocation();
            }
            else if (coordinates == "manual")
            {
                alert("chooseMethod manual");
                var latitude = form.latitude.value;
                var longitude = form.longitude.value;

                var NSlat;
                for (i = 0; i < 2; i++)
                {
                    if (form.NS[i].checked)
                    {
                        NSlat = form.NS[i].value;
                    }
                }
                if (NSlat == "south")
                {
                    latitude = -1.0 * latitude;
                }

                var EWlong;
                for (i = 0; i < 2; i++)
                {
                    if (form.EW[i].checked)
                    {
                        EWlong = form.EW[i].value;
                    }
                }
                if (EWlong == "east")
                {
                    longitude = -1.0 * longitude;
                }

                var locElev = form.landelev.value * 1.0000;
                var elevUnits;
                for (i = 0; i < 2; i++)
                {
                    if (form.elevunits[i].checked)
                    {
                        elevUnits = form.elevunits[i].value;
                    }
                }
                if (elevUnits == "meters")
                {
                    locElev = locElev * 3.2808;
                }
                
                if (Math.abs(latitude) > 48.5)
                {
                    if(latitude > 0)
                    {
                        latitude = 48.5000;
                    }
                    else
                    {
                        latitude = -48.5000;
                    }
                }
                
                document.getElementById("data25").innerHTML = latitude;
                document.getElementById("data26").innerHTML = longitude;
                document.getElementById("data28").innerHTML = locElev;
                
                if (latitude > 0)
                {
                    var NSlat = "N";
                }
                else if (latitude < 0)
                {
                    NSlat = "S";
                }
                else
                {
                    NSlat = "EQ"
                }

                if (longitude < 0)
                {
                    var EWlong = "E";
                }
                else if (longitude > 0)
                {
                    EWlong = "W";
                }
                else
                {
                    EWlong = "PM"
                }

                document.getElementById("data36").innerHTML = NSlat;
                document.getElementById("data37").innerHTML = EWlong;
                
                var day;
                var month;
                var year;
                if (dateCheck == "auto")
                {
                    alert("chooseMethod manual auto Date");
                    var dateData = new Date();

                    year = dateData.getFullYear();
                    month = dateData.getMonth() + 1;
                    day = dateData.getDate();
                    
                    timezoneIndex = form.timezones.selectedIndex;
                    timezone = form.timezones.options[timezoneIndex].value;
                    
                    if (form.ManualDST.checked)
                    {
                        timezone = Number(timezone) + 1.0;
                    }
                    else
                    {
                        timezone = timezone;
                    }
                }
                else
                {
                    alert("chooseMethod manual manual Date");
                    var dateData = new Date(form.dateInput.value);
                    year = dateData.getFullYear();
                    month = dateData.getMonth() + 1;
                    day = dateData.getDate() + 1;

                    if (month == 10 || month == 8 || month == 7 || month == 5 || month == 3 || month == 1)
                    {
                        if (day > 31)
                        {
                            month = month + 1;
                            day = 1;
                        }
                    }
                    if (month == 12)
                    {
                        if (day > 31)
                        {
                            month = 1;
                            day = 1;
                        }
                    }
                    if (month == 11 || month == 9 || month == 6 || month == 4)
                    {
                        if (day > 30)
                        {
                            month = month + 1;
                            day = 1;
                        }
                    }
                    if (month == 2)
                    {
                        if (isLeapYear(year))
                        {
                            if (day > 29)
                            {
                                month = 3;
                                day = 1;
                            }
                        }
                        else
                        {
                            if (day > 28)
                            {
                                month = 3;
                                day = 1;
                            }
                        }
                    }
                    
                    document.getElementById("data27y").innerHTML = year;
                    document.getElementById("data27m").innerHTML = month;
                    document.getElementById("data27d").innerHTML = day;
                    
                    timezoneIndex = form.timezones.selectedIndex;
                    timezone = form.timezones.options[timezoneIndex].value;

                    if (form.ManualDST.checked)
                    {
                        timezone = Number(timezone) + 1.0;
                    }
                    else
                    {
                        timezone = timezone;
                    }
                }
                var dDelta = 21;
                for (i = 0; i < 3; i++)
                {
                    if (form.noonMode[i].checked)
                    {
                        dDelta = Number(form.noonMode[i].value);
                    }
                }

                var aDelta = 1;
                for (i = 0; i < 2; i++)
                {
                    if (form.afternoonMode[i].checked)
                    {
                        aDelta = Number(form.afternoonMode[i].value);
                    }
                }

                var sDelta = 12;
                for (i = 0; i < 2; i++)
                {
                    if (form.astroMode[i].checked)
                    {
                        sDelta = Number(form.astroMode[i].value);
                    }
                }

                var iDelta = 15;
                for (i = 0; i < 2; i++)
                {
                    if (form.nightMode[i].checked)
                    {
                        iDelta = Number(form.nightMode[i].value);
                    }
                }
                
                
                solarTimeDetails = calcSolarTimes(latitude, longitude, locElev, day, month, year, timezone, dDelta, aDelta, sDelta, iDelta);
            
                document.getElementById("data35").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[35]));
                document.getElementById("data3").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[2]));
                document.getElementById("data4").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[3]));
                document.getElementById("data6").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[5]));
                document.getElementById("data12").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[11]));
                document.getElementById("data16").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[15]));
                document.getElementById("data20").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[19]));
                document.getElementById("data21").innerHTML = MilToAmPm(timeToMinutes(solarTimeDetails[20]));

                localStorage.setItem("elevation", solarTimeDetails[36]);
                localStorage.setItem("shadowAzimuth", solarTimeDetails[37]);
                localStorage.setItem("latitude", latitude);
                localStorage.setItem("longitude", longitude);
                localStorage.setItem("currentTime", currentMinutes);

                localStorage.setItem("astroTime", timeToMinutes(solarTimeDetails[3]));
                localStorage.setItem("sunriseTime", timeToMinutes(solarTimeDetails[5]));
                localStorage.setItem("noonTime", timeToMinutes(solarTimeDetails[11]));
                localStorage.setItem("afternoonTime", timeToMinutes(solarTimeDetails[15]));
                localStorage.setItem("sunsetTime", timeToMinutes(solarTimeDetails[19]));
                localStorage.setItem("nightTime", timeToMinutes(solarTimeDetails[20]));
                localStorage.setItem("morningTime", timeToMinutes(solarTimeDetails[39]));

                localStorage.setItem("transitTime", solarTimeDetails[38]);


                localStorage.setItem("transitElev", solarTimeDetails[40]);
                localStorage.setItem("currentMinutes", currentMinutes);
                var SunAltitude = [];
                SunAltitude = localStorage.getItem("elevation").split(",");
                document.getElementById("currentAlt").innerHTML = Number(SunAltitude[currentMinutes]).toFixed(1);
            } //end of manual
        } //end of chooseMethod
        
        //loading saved form data into form
        function dataLoad() 
        {
            if (typeof(Storage) !== "undefined")
            {
                if (localStorage.getItem('settingsObject') !== null) 
                {
                    alert("in dataLoad");
                    var inputParse = JSON.parse(localStorage.getItem('settingsObject'));
                    $.each(inputParse, function(key, value) {
                      var field = document.querySelector("[name=" + key + "]");
                      if (field.type == 'radio' || field.type == 'checkbox') {
                        field.checked = field.value == value;
                      } else {
                        field.value = value;
                      }
                    });
                }
            }
            else 
            {
              document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
            }
        } //end of dataLoad
        
        // Saving data from form

        function CacheData() 
        {
            if (typeof(Storage) !== "undefined")
            {   
                jQuery.fn.serializeObject = function() {
                    var formData = {};
                    var formArray = this.serializeArray();
                    for (var i = 0, n = formArray.length; i < n; ++i)
                        formData[formArray[i].name] = formArray[i].value;
                    return formData;
                };
                
                var formObject = $('#settingsInput').serializeObject();
                localStorage.setItem('settingsObject', JSON.stringify(formObject));
                
                return JSON.stringify(formObject);
            }
            else 
            {
                document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Storage...";
            }
        } //end of CacheData
    
    </script>
    
</body>
</html>

I have searched stackoverflow for many solutions but can’t find one that helps.

i have tired using onSubmit="return false;" in the form tag , but then the manual selections do not get used.

I have also tried using onpageopen instead of onload but that did not help either.

2

Answers


  1. You need to listen for the submit event on the form element and call the preventDefault function to prevent the regular form submission behaviour.

    You can do this with addEventListener('submit') or onsubmit.

    See example below.

    function printName() {
      const name = document.querySelector('input[name="name"]').value
      console.log(name)
    }
    
    function printAge() {
      const age = document.querySelector('input[name="age"]').value
      console.log(age)
    }
    
    function handleSubmit(event) {
      console.log('preventing form submit')
      event.preventDefault()
    }
    label {
      display: block;
      margin-bottom: 0.5em;
    }
    <form onsubmit="handleSubmit(event)">
      <label>Name: <input type="text" name="name" placeholder="name"></label>
      <label>Age: <input type="text" name="age" placeholder="age"></label>
      <button onclick="printName()">Print Name</button>
      <button onclick="printAge()">Print Age</button>
    </form>
    Login or Signup to reply.
  2. First you should have researched more, there are lots of answers for you here on StackOverflow. (a beautiful example of a solution to your question)

    Try to insert this on buttons type="button" and handle submit event, like this:

    1. using JQuery:
    <!-- Your HTML form here -->
    <form id="settingsInput" class="dropdown contents" autocomplete="on">
        <!-- Your HTML form here -->
        <div class="set-section">
            <button type="button" name="solartimes" value=" Save " onclick="chooseMethod(this.form)">Save</button>
        </div>
        <div class="update-section">
            <button type="button" name="updatesolartimes" value=" Update " onclick="chooseMethod(this.form)">Update</button>
        </div>
        <div class="reset-section">
            <button type="reset" value=" Reset ">Reset</button>
        </div>
        <!-- Your HTML form here -->
    </form>
    <script>
        $('#settingsInput').on('submit', function(e) {
            e.preventDefault();
            //...
        });
        //Rest of your js code here...
    </script>
    <!-- Your HTML form here -->
    1. Pure JS
    <!-- Your HTML form here -->
    <form id="settingsInput" class="dropdown contents" autocomplete="on">
        <!-- Your HTML form here -->
        <div class="set-section">
            <button type="button" name="solartimes" value=" Save " onclick="chooseMethod(this.form)">Save</button>
        </div>
        <div class="update-section">
            <button type="button" name="updatesolartimes" value=" Update " onclick="chooseMethod(this.form)">Update</button>
        </div>
        <div class="reset-section">
            <button type="reset" value=" Reset ">Reset</button>
        </div>
        <!-- Your HTML form here -->
    </form>
    <script>
        document.getElementById("settingsInput").addEventListener("submit", function(e) {
            e.preventDefault();
            //...
        });
        //Rest of your js code here...
    </script>
    <!-- Your HTML form here -->

    Hope this help!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search