Fefee.33 Fefee.33 - 7 months ago 14
HTML Question

Javascript assign value to HTML field

I am trying to save an HTML field (for later use in a form) from a JS script.

This is the code:

Form

<form class="new_client" id="new_client" action="/clients" accept-charset="UTF-8" method="post">
<div class="form-group">
<input class="form-input" type="hidden" name="client[city]" id="client_city">
</div>
<div class="form-group">
<input class="form-input" type="hidden" name="client[address]" id="client_address">
</div>
<div id="locationField">
<input autocomplete="off" class="autocomplete" placeholder="Enter your address" type="text">
</div>
<div class="text-center">
<button class="btn button-general ">Save</button>
</div>
</form>


And the javascript:

function configureGeoAutocomplete(context) {
if( context === undefined ) {
context = $('body');
}
var element = context.find('.autocomplete')
//It doesn't really matter what this line does, it's from Google Places API
var autocomplete = new google.maps.places.Autocomplete(
element[0], {types: ['geocode']});

autocomplete.addListener('place_changed', fillInAddress)
}

function fillInAddress() {
var client_address = autocomplete.getPlace().formatted_address;
document.getElementById("client_address").value = client_address;
}


The javascript is queried when loading the modal in which the form is

jQuery(function() {
$('div.modal').on('loaded.bs.modal', function(e) {
configureGeoAutocomplete(context);
}
}


I wanna save that client_address to the text field so when the form is submitted I can have that information.

Answer

Apparently, for some reason, if I searched the element by ID it was not saving the information on the field. If I istead search by class:

function fillInAddress() {
  var place = autocomplete.getPlace();

  $(".client-address").val(place.formatted_address);
}

It works as intended.