Reputation: 74
Basically I'm creating dynamical fields for example there may be 10 fields by using the jquery. And I want to add google address autocomplete on all 10 dynamically created fields. But this code is not working.
var html += '<div class="form-group">';
html += '<label class="control-label">'+field.label+'</label>';
html += '<input class="form-control address-auto-complete"
name="'+field.name+'[]" type="text" />';
html += '</div>';
$('#load-case-fields').html(html);
var a = new google.maps.places.Autocomplete($('.address-auto-complete'));
I'm getting this error with above code.
InvalidValueError: not an instance of HTMLInputElement
Upvotes: 2
Views: 2827
Reputation: 6579
$('.selector') gives you an jquery Element, but you want the underlying Input so try $('.asd')[0] or use plain JavaScript
var input = document.getElementById('yourInput');
var autocomplete = new google.maps.places.Autocomplete(input);
Upvotes: 0
Reputation: 10075
You can try in pure JS
Fiddle demo
function initialize() {
parentDiv = document.getElementById('variable');
for (var i = 0; i < 10; i++) { //dynamically create 10 inputs
var formGroupDiv = document.createElement('div')
formGroupDiv.classList.add('form-group')
parentDiv.appendChild(formGroupDiv)
var labels = document.createElement('label')
labels.classList.add('control-label')
labels.innerHTML = 'LABEL ' + i
formGroupDiv.appendChild(labels)
var input = document.createElement('input');
input.classList.add('form-control', 'address-auto-complete')
input.setAttribute('placeholder', "Enter your address")
input.setAttribute('type', "text")
formGroupDiv.appendChild(input)
}
var variableAuto = document.getElementsByClassName('address-auto-complete');
for (var j = 0; j < variableAuto.length; j++) { //dynamically initialize autocomplete to input elements
new google.maps.places.Autocomplete(
(variableAuto[j]), {
types: ['geocode']
});
}
}
initialize();
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<div class="col-sm-12" id="variable">
</div>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
Upvotes: 1