Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 14 of 14
  1. #1
    New Coder
    Join Date
    Jan 2016
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts

    Input on select update not working

    Hi guys,

    I am using google maps auto complete function for searching locations. Now the input field is almost working the way i want it to be. When you search for a location and click on that location from the drop down menu the prayer time table will not update its times to the correct location selected, but only if you click outside the input field anywhere on the page the time table wis updated whit the chosen location. Is there any possible way so when ever i click the location from the google maps auto complete function so the table gets updated with that location. instead of clicking again on the page.

    my code is on codepen please take a look and see what i mean. So basically i want the time table to update it self right away when a location has been selected and not clicking on the page again to get the searched location.

    my codepen

    Code:
    <!DOCTYPE html>
    <html style="height: 100%;">
    
    <head>
      <meta http-equiv="content-type" content="text/html; charset=UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    
    <script
    			  src="https://code.jquery.com/jquery-3.1.1.js"
    			  integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA="
    			  crossorigin="anonymous"></script>
      <script type="text/javascript" src="http://praytimes.org/code/v2/js/PrayTimes.js"></script>
    
    
      <link rel='stylesheet prefetch' href='http://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css'>
    
        
    
    
    <script src='https://maps.googleapis.com/maps/api/js?v=3&libraries=places'></script>
      <script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'></script>
    <script src='http://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js'></script>
    
    
     
    
    
      <title> Monthly Prayer Timetable </title>
      <style>
        body, tr, form {font-size: 12px; color: #404040; text-align: center; margin: 0; padding: 0}
        pre {font-family: courier, serif, size: 10pt; margin: 0px 8px;}
        input {font-size: 12px;}
        .sheader {background:#eef; border-bottom: 1px solid #ddd; padding: 7px;}
        .caption {font-size: 20px; color: #d95722; text-align: center; width: 10em;}
        .arrow {font-weight: bold; text-decoration: none; color: #3D3D3D; }
        .arrow:hover {text-decoration: underline;}
        .command {font-weight: bold; text-decoration: none; color: #AAAAAA; }
        .command:hover {text-decoration: underline;}
        .timetable {border-width: 1px; border-style: outset; border-collapse: collapse; border-color: gray; margin: 0 auto;}
        .timetable td {border-width: 1px; border-spacing: 1px; padding: 1px; border-style: inset; border-color: #CCCCCC;}
        .head-row {color: black; background-color: #eef;}
        .today-row {background-color: #000; color: #fff}
    	
    
    }
    
      </style>
    
    
    </head>
    <script>
    (function($) {
    
      var debug = function(msgOrObject) {
        if (typeof(msgOrObject) === 'object') {
          msgOrObject = JSON.stringify(msgOrObject);
        }
        $('.console').html(msgOrObject);
      }
    
      function bindAutocomplete() {
    
        var acService = new google.maps.places.AutocompleteService(),
          placesService = new google.maps.places.PlacesService(document.createElement('div')),
            searchTypes = ['geocode'];
    
        $("input#location").autocomplete({
          source: function(req, resp) {
    
            acService.getPlacePredictions({
              input: req.term,
              types: searchTypes
            }, function(places, status) {
              console.log('places', places);
              if (status === google.maps.places.PlacesServiceStatus.OK) {
                var _places = [];
                for (var i = 0; i < places.length; ++i) {
                  _places.push({
                    id: places[i].place_id,
                    value: places[i].description,
                    label: places[i].description
                  });
                }
                resp(_places);
              }
            });
          },
          select: function(e, o) {
            placesService.getDetails({
              placeId: o.item.id
            }, function(place, status) {
              console.log("details", place);
              if (status === google.maps.places.PlacesServiceStatus.OK) {
                debug(o.item.value +
                  '\n is located at \n ' +
                  place.geometry.location.toUrlValue());
              }
            });
    
          }
        });
      }
    
      // ** INITIALIZE ** //
      $(function() {
        try {
          bindAutocomplete();
          debug("initialized");      
        } catch (e) {
          debug({error: e});
        }
      });
    
    }(jQuery));
    
    </script>
    
    
            <script>
            var key = 'AIzaSyB0Itj_hV1-tkIczLJ9kQiJNePyoaDfd4k';
            var x=document.getElementById("detected_location");
    
    		function getLocation()
              {
              if (navigator.geolocation)
                {
                navigator.geolocation.getCurrentPosition(showPosition);
                }
              else{ x.innerHTML="Geolocation is not supported by this browser. Please enter your location below:";}
              }
            function showPosition(position)
              {
                  var lati = position.coords.latitude; var longi = position.coords.longitude;
                  x.innerHTML="Latitude: " + lati +
                  "<br>Longitude: " + longi;
    
                  // var loc = document.getElementById('location');
                  // loc.value= lati + ',' + longi;
                  document.getElementById('latitude').value = lati;
                  document.getElementById('longitude').value = longi;
                  jQuery('.formatted_loc').html(lati+","+longi);
                  getGoogleLoc(lati,longi,false);
                  ga('send', {
                    'hitType': 'event',          // Required.
                    'eventCategory': 'AJAX',   // Required.
                    'eventAction': 'geolocation',      // Required.
                    'eventLabel': 'Location Coords',
                    'eventValue': lati+','+longi
                  });
                  update();
              }
    		
              function getGoogleLoc(lati,longi,address){
                  !!(address) ?address = jQuery('#location').val() : address = false; 
                  var dataString = {
                      sensor: true,
                      latlng: lati+","+longi
                    };
    
                  if(address) dataString['address'] = address;
                  var req = jQuery.ajax({
                    url: "https://maps.googleapis.com/maps/api/geocode/json",
                    type: "GET",
                    cache: false,
                    data: dataString,
                    dataType: "JSON"
                  });
                  req.done(function(data){
                      console.log(data);
                      if(data && data.results && data.results.length) var formattedLoc = data.results[0].formatted_address;
                      jQuery('.formatted_loc').html(formattedLoc);
                      var updatedLati = data.results[0].geometry.location.lat;
                      var updatedLongi = data.results[0].geometry.location.lng;
                      jQuery('#latitude').val(updatedLati);
                      jQuery('#longitude').val(updatedLongi);
                      update();
                      getTimeZone(updatedLati,updatedLongi);
                      ga('send', {
                        'hitType': 'event',          // Required.
                        'eventCategory': 'AJAX',   // Required.
                        'eventAction': 'Google Maps API',      // Required.
                        'eventLabel': 'Geocoder Location',
                        'eventValue': formattedLoc
                      });
                    });
              }
              function getTimeZone(lati,longi){
                jQuery.getJSON('https://maps.googleapis.com/maps/api/timezone/json?location='+lati+','+longi+'&timestamp='+ +new Date()/1000, function(data){
    
                  var dst = data.dstOffset/3600;
                  var tz = data.rawOffset/3600;
                  jQuery('#dst').val(dst);
                  jQuery('#timezone').val(tz);
                  update();
    
                  ga('send', {
                        'hitType': 'event',          // Required.
                        'eventCategory': 'AJAX',   // Required.
                        'eventAction': 'Google Maps API',      // Required.
                        'eventLabel': 'Timezone API',
                        'eventValue': tz
                      });
    
                })
              }
    
              </script>
    
    		     
    
    
    
    <input name="location" id="location" value="" onchange="getGoogleLoc(false,false,true)" type="text" placeholder="enter location..."/>
    
    <div class="console"></div>
    
    
    
              <h3 class="formatted_loc">Amsterdam, Netherlands</h3>
      
    
    <div class="sheader">
    <form class="form" action="javascript:update();">
      Latitude: <input value="52.3702157" id="latitude" size="2" onchange="update();" type="text">&nbsp;
      Longitude: <input value="4.8951679" id="longitude" size="2" onchange="update();" type="text">&nbsp;
      Time Zone: <input value="1" id="timezone" size="2" onchange="update();" type="text">&nbsp;
      DST:
      <select id="dst" size="1" style="font-size: 12px;" onchange="update()">
        <option value="auto">Auto</option>
        <option value="0" selected="selected">0</option>
        <option value="1">1</option>
        </select>&nbsp;
      Method:
      <select id="method" size="1" style="font-size: 12px;" onchange="update()">
        <option value="MWL" selected="selected">Muslim World League (MWL)</option>
        <option value="ISNA">Islamic Society of North America (ISNA)</option>
        <option value="Egypt">Egyptian General Authority of Survey</option>
        <option value="Makkah">Umm al-Qura University, Makkah</option>
        <option value="Karachi">University of Islamic Sciences, Karachi</option>
        <option value="Jafari">Shia Ithna-Ashari (Jafari)</option>
        <option value="Tehran">Institute of Geophysics, University of Tehran</option>
        </select>
    </form>
    </div>
    <br>
    
    <div>
      <table align="center">
      <tbody><tr>
        <td><a href="javascript:displayMonth(-1)" class="arrow">&lt;&lt;</a></td>
        <td id="table-title" class="caption">November 2016</td>
        <td><a href="javascript:displayMonth(+1)" class="arrow">&gt;&gt;</a></td>
      </tr>
      </tbody></table>
    
      <br>
      <table id="timetable" class="timetable"></table>
    
      <div style="margin-top: 7px" align="center">
        Source: <a href="http://praytimes.org/" class="command">PrayTimes.org</a> |
        Time Format: <a id="time-format" href="javascript:switchFormat(1)" title="Change clock format" class="command">24-hour</a>
      </div>
    
    </div>
    
    <br>
    
    <script type="text/javascript">
    
      var currentDate = new Date();
      var timeFormat = 2;
      switchFormat(0);
    
      // display monthly timetable
      function displayMonth(offset) {
      		prayTimes.setMethod('MWL');
    	    prayTimes.adjust( {asr: 'Standard', isha: '90 min'} );
    	    prayTimes.tune( {imsak: 0, fajr: -90, sunrise: 0, dhuhr: 0, asr: 0, maghrib: 0, isha: 0} );
      
        var lat = $('latitude').value;
        var lng = $('longitude').value;
        var timeZone = $('timezone').value;
        var dst = $('dst').value;
        var method = $('method').value;
    
        
        currentDate.setMonth(currentDate.getMonth()+ 1* offset);
        var month = currentDate.getMonth();
        var year = currentDate.getFullYear();
        var title = monthFullName(month)+ ' '+ year;
        $('table-title').innerHTML = title;
        makeTable(year, month, lat, lng, timeZone, dst);
      }
    
      // make monthly timetable
      function makeTable(year, month, lat, lng, timeZone, dst) {
        var items = {day: 'Day', fajr: 'Fajr', sunrise: 'Sunrise',
              dhuhr: 'Dhuhr', asr: 'Asr', // sunset: 'Sunset',
              maghrib: 'Maghrib', isha: 'Isha'};
    
        var tbody = document.createElement('tbody');
        tbody.appendChild(makeTableRow(items, items, 'head-row'));
    
        var date = new Date(year, month, 1);
        var endDate = new Date(year, month+ 1, 1);
        var format = timeFormat ? '12hNS' : '24h';
    
        while (date < endDate) {
          var times = prayTimes.getTimes(date, [lat, lng], timeZone, dst, format);
          times.day = date.getDate();
          var today = new Date();
          var isToday = (date.getMonth() == today.getMonth()) && (date.getDate() == today.getDate());
          var klass = isToday ? 'today-row' : '';
          tbody.appendChild(makeTableRow(times, items, klass));
          date.setDate(date.getDate()+ 1);  // next day
        }
        removeAllChild($('timetable'));
        $('timetable').appendChild(tbody);
      }
    
      // make a table row
      function makeTableRow(data, items, klass) {
        var row = document.createElement('tr');
        for (var i in items) {
          var cell = document.createElement('td');
          cell.innerHTML = data[i];
          cell.style.width = i=='day' ? '2.5em' : '3.7em';
          row.appendChild(cell);
        }
        row.className = klass;
        return row;
      }
    
      // remove all children of a node
      function removeAllChild(node) {
        if (node == undefined || node == null)
          return;
    
        while (node.firstChild)
          node.removeChild(node.firstChild);
      }
    
      // switch time format
      function switchFormat(offset) {
        var formats = ['24-hour', '12-hour'];
        timeFormat = (timeFormat+ offset)% 2;
        $('time-format').innerHTML = formats[timeFormat];
        update();
      }
    
      // update table
      function update() {
        displayMonth(0);
      }
    
      // return month full name
      function monthFullName(month) {
        var monthName = new Array('January', 'February', 'March', 'April', 'May', 'June',
                'July', 'August', 'September', 'October', 'November', 'December');
        return monthName[month];
      }
    
      function $(id) {
        return document.getElementById(id);
      }
    
    
    </script>
    
    </body>
    </html>

  2. #2
    Master Coder sunfighter's Avatar
    Join Date
    Jan 2011
    Location
    Washington
    Posts
    7,474
    Thanks
    31
    Thanked 1,008 Times in 1,005 Posts
    mio510
    You've placed two JS scripts after the </head> tag. Maybe you should move all scripts to the end of the HTML. Most importantly is the absence of a <body> tag.

    In your first <input> you use onchange="getGoogleLoc(false,false,true)" which is why you need to click in the page. That should be in the pop up that gives you the choice of locations and it should be changed to a onclick="" someplace after you add the title to the page.
    Evolution - The non-random survival of random variants.
    Physics is actually atoms trying to understand themselves.

  3. #3
    New Coder
    Join Date
    Jan 2016
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Thanks for your rely. I did not notice how messy this code was after you pointed these things out. Now i did what you suggested to do, but still having problems where the time table is not updated after selecting a location. Changing the onchange= to onclick= i have to click inside the input field now then the time table is updated. Hope you can tell me what piece of code i still can change to make this work.

  4. #4
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Location
    Here
    Posts
    3,685
    Thanks
    58
    Thanked 665 Times in 660 Posts
    If the autocomplete has a select callback (which you are already using) why not use it to call the function that updates the table?

  5. #5
    New Coder
    Join Date
    Jan 2016
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts
    If i am not mistaking your talking about this part of the code:

    Code:
          select: function(e, o) {
            placesService.getDetails({
              placeId: o.item.id
            }, function(place, status) {
              console.log("details", place);
              if (status === google.maps.places.PlacesServiceStatus.OK) {
                debug(o.item.value +
                  '\n is located at \n ' +
                  place.geometry.location.toUrlValue());
              }
            });
    
          }
    i am not an expert in coding so every help i can get would be great. What changes should i make to this, i know the function that updates the timetable is getGoogleLoc

  6. #6
    New Coder
    Join Date
    Jan 2016
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Still waiting if someone can help me out with this.

  7. #7
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Location
    Here
    Posts
    3,685
    Thanks
    58
    Thanked 665 Times in 660 Posts
    I am talking about putting this:

    getGoogleLoc(false,false,true);

    inside the select method that you posted above

    You are allowed to try things, you know. You're not going to break the internet

  8. Users who have thanked xelawho for this post:

    mio510 (12-25-2016)

  9. #8
    New Coder
    Join Date
    Jan 2016
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts
    hhhh ok will try some things out. but the autocomplete function does not work when i change the select method. i think i might be doing something wrong.

  10. #9
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Location
    Here
    Posts
    3,685
    Thanks
    58
    Thanked 665 Times in 660 Posts
    Have a look at the error console, post some code

  11. Users who have thanked xelawho for this post:

    mio510 (12-25-2016)

  12. #10
    New Coder
    Join Date
    Jan 2016
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Tried this code out but it seems it has no effect. i did not modify the select method because that code broke everything when changing the smallest thing. instead i used this:

    Code:
    <script>
    $('input').on('change', function getGoogleLoc(false,false,true) {
      
    })
    </script>
    but still figuring out whats wrong with it. I might use a different code for the google maps autocomplete maybe that will work.
    Last edited by mio510; 12-24-2016 at 04:02 AM.

  13. #11
    Senior Coder xelawho's Avatar
    Join Date
    Nov 2010
    Location
    Here
    Posts
    3,685
    Thanks
    58
    Thanked 665 Times in 660 Posts
    the code posted in #1 works for me if you remove the calls to ga and put the getGoogleLoc call in the select method of the autocomplete. Putting an onchange event listener on an input is nover going to achieve what you want as it will always wait for the input to lose focus before firing the function

  14. Users who have thanked xelawho for this post:

    mio510 (12-25-2016)

  15. #12
    New Coder
    Join Date
    Jan 2016
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Could you please paste the code here so i can see what you have done exactly. Or the modified codepen if possible

    i tried this : in the select method but it still is not working for me

    Code:
          select: function getGoogleLoc {
    
    
          }
    and also removed the ga calls. still the same time table is does not update when a location has been selected from the google maps auto complete
    Last edited by mio510; 12-25-2016 at 09:02 PM.

  16. #13
    New Coder
    Join Date
    Jan 2016
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Hi,
    Still waiting for the modified codepen link. If possible please post the code here .

  17. #14
    New Coder
    Join Date
    Jan 2016
    Posts
    22
    Thanks
    5
    Thanked 0 Times in 0 Posts
    Still waiting if no one can reply otherwise this topic can be closed. Thanks


 

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •