Input shows previous value, after setting value - javascript

I am making a form with yandex maps integration. I need the value of input to be changed after user picks some point on map. Here is code:
function setPlace(c){
//c - coordinates
var geocoder = ymaps.geocode(c, {kind: "locality"});
geocoder.then(function(res){
var city = res.geoObjects.get(0).properties.get("name");
var inpCity = document.getElementById(idCity);
inpCity.value = city;
});
}
So the problem is I am setting value of input properly (checked in console). But on the page input always shows previous chosen value.

Related

Google Maps API Autocomplete search without selecting from dropdown [duplicate]

This question already has answers here:
Google Maps API: How do you ensure that the Google Maps Autocomplete text is an actual address before submitting? [duplicate]
(2 answers)
Closed 2 years ago.
I am using Google Maps API and the Autocomplete search feature. Currently, you must begin typing a location(city, state, zip, etc.) and then select a result from the dropdown for the map to center at that location. However, I would like to make this fool proof and set it up so that if someone types just a city or just a state and hits "enter" without selecting an Autocomplete result, it will still work. For instance, if someone types "New York" and hits "enter" without selecting a result in the dropdown, it will still center on New York.
I'm assuming this is accomplished by grabbing the first result from the Autocomplete dropdown if one is not selected manually.
I've added an event listener for the submission of the form, but not sure how to pass the first result into the "place" variable.
Here is my code:
function searchBar(map) {
var input = document.getElementById('search-input');
var searchform = document.getElementById('search-form');
var place;
var options = {componentRestrictions: {country: 'us'}};
var autocomplete = new google.maps.places.Autocomplete(input, options);
//Add listener to detect autocomplete selection
google.maps.event.addListener(autocomplete, 'place_changed', function () {
place = autocomplete.getPlace();
center = new google.maps.LatLng(place.geometry.location.lat(),place.geometry.location.lng());
map.setCenter(center);
map.setZoom(5);
});
//Add listener to search
searchform.addEventListener('submit', function() {
center = new google.maps.LatLng(place.geometry.location.lat(),place.geometry.location.lng());
map.setCenter(center);
map.setZoom(5);
});
//Reset the inpout box on click
input.addEventListener('click', function(){
input.value = "";
});
};
And here is a JSFiddle for experimentation.
There is no implemented way to access the places in the dropdown. Basically what you see in the dropdown are not places, there are only predictions. The details for a prediction will be loaded when you select a prediction.
So you must select a prediction programmatically.
How to achieve it:
Another way than clicking on a prediction is to use the down-key, the keycode is 40. The API listens to keydown-events of the input.
So when you hit enter:
trigger keydown with a keycode 40(down)
trigger keydown with a keycode 13(enter)
google.maps.event.addDomListener(input,'keydown',function(e){
if(e.keyCode===13 && !e.triggered){
google.maps.event.trigger(this,'keydown',{keyCode:40})
google.maps.event.trigger(this,'keydown',{keyCode:13,triggered:true})
}
});
Note: to avoid a infinite loop for the enter I've added a custom property triggered, so I'm able to bypass the triggered keydown inside the function.
Demo: http://jsfiddle.net/4nr4tdwz/1/
I added a filter to avoid keydown being triggered when user has already select any result from the autocomplete:
google.maps.event.addDomListener(input,'keydown',function(e){
if(e.keyCode===13 && $('.pac-item-selected').length == 0 && !e.triggered){
google.maps.event.trigger(this,'keydown',{keyCode:40})
google.maps.event.trigger(this,'keydown',{keyCode:13,triggered:true})
}
});
Helper function for setting initial/default location programmatically - e.g. from geolocation API.
var triggerLocation = function(autocompleteInput, addressString) {
var $locationInput = $(autocompleteInput).val(addressString).trigger('focus');
var maxTries = 500;
var autocompleteSelectionInterval = setInterval(function() {
if (!--maxTries) {
clearInterval(autocompleteSelectionInterval);
}
if ($('.pac-container .pac-item').length) {
google.maps.event.trigger($locationInput[0], 'keydown', {
keyCode : 40
});
google.maps.event.trigger($locationInput[0], 'keydown', {
keyCode : 13
});
clearInterval(autocompleteSelectionInterval);
}
}, 10);
};
Example:
var autocomplete = new google.maps.places.Autocomplete($('#location')[0]);
triggerLocation('#location', 'New York');

Compare value in combo box with value in hidden field

I have several telerik radComboboxes and each has a corresponding hidden field.
The combos have an id prefix of cmb and their hidden field have a prefix of hd. I used these to detect if any combo box has had its value changed or if I need to reset the combo back to its initial value. I have the following JavaScript which is fired onClienSelectedIndexChanged...
function cmbSelectedIndexChanged(sender, eventArgs) {
            var selectedItem = eventArgs.get_item();
            var selectedItemText = selectedItem != null ? selectedItem.get_text() : sender.get_text();
            var hd = sender.attr('id').replace("cmb", "hd");
            if (selectedItemText !== $('#' + hd).val()) {
                registerChange();
            }
        }
 
I get an error - object doesn't this property or method - on the line beginning var hd
What am I doing wrong...?
You need to be searching for the ClientId of the control therefore the code will not work. Instead of
var hd = sender.attr('id').replace("cmb", "hd");
You should try something along the lines of:
var hd = sender.get_id().replace("cmb", "hd").replace(/_/,"$");
The above code will convert the client id of the telerik combo box into the "name" attribute of the element of the asp hidden control. I believe the code below should resolve the problem described (I apologize for the extra comments I was using this as a teaching aid earlier and thought it might be beneficial to other users)
function cmbSelectedIndexChanged(sender, eventArgs) {
// Get Selected Item
var selectedItem = eventArgs.get_item();
// Get Selected Text
var selectedItemText = selectedItem != null ? selectedItem.get_text() : sender.get_text();
// Convert Telerik element id to Asp Control name
var hd = sender.get_id().replace("cmb", "hd").replace(/_/g,"$");
// Compare the asp:HiddenField value to the selected text
if (selectedItemText !== document.getElementsByName( hd)[0].value) {
registerChange();
}
}
When debugging this locally I didn't have JQuery registered on the page so my updated function uses the .getElementsByName function instead of the JQuery equivalent e.g. $('[name="' + hd + '"]').

Store input value as a var and display it

This is the code I am working from:
http://jsfiddle.net/DYfbg/12/
If you click "map" then try typing a placename it gives you autocomplete suggestions. Then if you click on one of these suggestions it tells you the co-ordinates in an alert box.
What I want to do is capture what is in the input box when the autocomplete option is clicked, and then store it as a variable. Then in the alert box, along with the co-ordinates, I want to print the input box variable into it.
I know this all sounds pretty simple but I am new to javascript so I would really appreciate some input.
This is the segment of code:
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
**// Store input box as variable**
if (!place.geometry) {
current_place = null;
alert('Cannot find place');
return;
} else {
current_place = place;
alert('Place is at:' + place.geometry.location);
**// Print input box varaible aswell**
} });
EDIT: This is as close as I could get without getting stuck:
// Set Autocomplete Location Variable equal to #loc input
$("#loc").val(ac_location);
// Print Autocomplete Variable
alert(ac_location);
In the "place" object returned with
var place = autocomplete.getPlace();
you have all info you need
Add a console.log and you'll see all infos returned.
For example:
var place = autocomplete.getPlace();
console.log(place);
window.myGlobalVar = place.name;
Edit based on notes below:
it seems original value of inputbox is actually stored in this property:
autocomplete.gm_accessors_.place.lf.d

Using action in Javascript to submit form

I'm trying to submit a form using javascript. This is the code I've used to set the action to the form and then submit it. These 2 lines are in the onclick method defined for a button.
document.form1.action = fin_string;
document.forms["form1"].submit();
The problem here is that the fin_string gets replaced by something else when I do this. For eg. when fin_string = "http://www.gmail.com" this works, however when I keep fin_string as some other string (relative to the current path with attached parameters) it gets changed. alert(fin_string), shows the string correctly but when I use the string to set the action on the form and submit it, it gets changed.
This is what I want the fin_string to be (relative to the current path)
remote-service/FeedMergerManualTrigger?locales=en_GB-en_SG&deleteOutputFile=Y&localFilePath=c:/go/
but this is what the browser goes to when I assign it an action and submit the form.
remote-service/FeedMergerManualTrigger?LMN=UK&ZJ=SG&localResourcesMode=on&EUPath=c:/go/&delete_op=Y.
Any idea what's going on?
Have such code instead, it will assign hidden form elements instead of adding to the query string thus it won't get changed:
var fin_string = "remote-service/FeedMergerManualTrigger";
var arrData = {"locales": "en_GB-en_SG", "deleteOutputFile": "Y", "localFilePath": "c:/go/"};
var oForm = document.forms["form1"];
oForm.action = fin_string;
for (var key in arrData)
AddOrUpdate(oForm, key, arrData[key]);
//encodeURIComponent(arrData[key])
oForm.submit();
function AddOrUpdate(oForm, sName, sValue) {
var oInput = oForm.elements[sName];
if (!oInput) {
oInput = document.createElement("input");
oInput.type = "hidden";
oInput.name = sName;
oForm.appendChild(oInput);
}
oInput.value = sValue;
}

jQuery removing elements from DOM put still reporting as present

I have an address finder system whereby a user enters a postcode, if postcode is validated then an address list is returned and displayed, they then select an address line, the list dissappears and then the address line is split further into some form inputs.
The issue i am facing is when they have been through the above process then cleared the postcode form field, hit the find address button and the address list re-appears.
Event though the list and parent tr have been removed from the DOM it is still reporting it is present as length 1?
My code is as follows:
jQuery
// when postcode validated display box
var $addressList = $("div#selectAddress > ul").length;
// if address list present show the address list
if ($addressList != 0) {
$("div#selectAddress").closest("tr").removeClass("hide");
}
// address list hidden by default
// if coming back to modify details then display address inputs
var $customerAddress = $("form#detailsForm input[name*='customerAddress']");
var $addressInputs = $.cookies.get('cpqbAddressInputs');
if ($addressInputs) {
if ($addressInputs == 'visible') {
$($customerAddress).closest("tr").removeClass("hide");
}
} else {
$($customerAddress).closest("tr").addClass("hide");
}
// Need to change form action URL to call post code web service
$("input.findAddress").live('click', function(){
var $postCode = encodeURI($("input#customerPostcode").val());
if ($postCode != "") {
var $formAction = "customerAction.do?searchAddress=searchAddress&custpc=" + $postCode;
$("form#detailsForm").attr("action", $formAction);
} else {
alert($addressList);}
});
// darker highlight when li is clicked
// split address string into corresponding inputs
$("div#selectAddress ul li").live('click', function(){
$(this).removeClass("addressHover");
//$("li.addressClick").removeClass("addressClick");
$(this).addClass("addressClick");
var $splitAddress = $(this).text().split(",");
$($customerAddress).each(function(){
var $inputCount = $(this).index("form#detailsForm input[name*='customerAddress']");
$(this).val($splitAddress[$inputCount]);
});
$($customerAddress).closest("tr").removeClass("hide");
$.cookies.set('cpqbAddressInputs', 'visible');
$(this).closest("tr").fadeOut(250, function() { $(this).remove(); });
});
I think you're running into the same issue I recently ran into. If you have a variable pointing to 5 DIV's (example: var divs = $('.mydivs');) and then you call jQuery's remove() on one of the DIV's, like so: divs.eq(0).remove() you'll see that divs.size() still returns 5 items. This is because remove() operates on the DOM. However... if after calling remove() you then re-set your variable: divs = $('.mydivs'); and get the size you'll now get the correct size of the array. I've added sample code displaying this below:
// get all 5 divs
var d = $('.dv');
// remove the first div
d.eq(0).remove();
// you would expect 4 but no, it's 5
alert(d.size());
// re-set the variable
d = $('.dv');
// now we get 4
alert(d.size());

Categories