I'm having a difficulty with WordPress form.
I am writing a code which will be working based on entries from WordPress form. But the issue is when I try passing values from the form to JS function using HTML, it works perfectly. But when I try to upload the script files and link the script file with form, then the issue begins.
<select name='city' class='city' id="field_cityname-0">
<option value>Location</option>
<option value='Option 1'>Option 1</option>
<option value='Option 2'>Option 2</option>
<option value='Option 3'>Option 3</option>
<option value='Option 4'>Option 4</option>
<option value='Option 5'>Option 5</option>
<option value='Option 6'>Option 6</option>
<option value='Option 7'>Option 7</option>
</select>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById("map"), {
//map settings
});
let markers = [];
const cities = {
//Map markers
};
const addmarker = (lat, lng, name ) => {
return new google.maps.Marker({
});
};
//Test function for check values passing or not
var newElement = document.getElementById("field_cityname-0");
newElement.addEventListener('change', function(){
console.log(this.value + " city selected");
});
document.querySelector('#field_cityname-0').addEventListener('change', function(e) {
e.preventDefault();
if( this.value != '' && cities.hasOwnProperty( this.value ) ) {
markers.forEach( mkr => mkr.setMap( null ) );
let obj = cities[ this.value ];
markers.push( addmarker( obj.lat, obj.lng, obj.name ) );
console.log("The city is "+this.value);
return true;
}
alert('Oh no ' + this.value + ' not found')
})
}
window.initMap = initMap;
With HTML select element, I changed the //Test function position from inside to outside the initMap function or from outside to inside, it worked perfectly. Passed values properly.
But with WordPress form if I change the position of //Test function from inside to outside the initMap function, the JS code received the data from form SELECT element. But if I put the //Test function again inside of the initMap function, it's not working. No values receiving from Form and I can't figure out why.
Is there a any way to pass the values when using with WordPress form? field_cityname-0 is the id of WordPress form select element.