document.getElementById().value not returning textbox value

Hello. I am trying to build a delivery optimization app with openstreetmaps, leaflet, javascript with a flask back-end.
The idea is that a delivery manager can click on a map to create a texbox(es) that indicates a delivery point(s) and what she
types in the textbox(es) as the size of the order(s). I am having trouble retrieving the values entered into the textboxes using
document.getElementById().value. I have a leaflet plug-in that I use to search for a location. I also have lists/arrays
that keep track/process the coordinates of the textboxes and the distribution centre from which orders are filled.
The list of the textbox coordinates is stringified and assigned to the value of a hidden textbox.

My code for creating the map looks like this:

  <body onLoad="javascript:init();">
   <div id="map"></div>
   <div id="map">
      <input type="button" id="btn1" value="Submit" />
	  <input type="hidden" id="coord1" value="" />
   <script language="javascript">
      	var map;
		var str;
		var dc_coords;
		var counter = 0;
		var coordinates = {};
		var customer_orders = {};
		var coords;
		var coords_array;
		function init() {
      	 map ='map');
      	 //add a tile layer to add to our map, in this case it's the 'standard' tile server
      	 L.tileLayer('http://{s}{z}/{x}/{y}.png', {
            attribution: '&copy; <a href="">OpenStreetMap</a> contributors',
            maxZoom: 18

         map.attributionControl.setPrefix(''); // Don't show the 'Powered by Leaflet' text. Attribution overload
		var nairobi = new L.LatLng(-1.28333,36.81667); // geographical point (longitude and latitude)
		map.setView(nairobi, 13);
			.bindPopup('Distribution<br> Centre')
		coordinates[counter] = nairobi;
		dc_coords = JSON.stringify(coordinates);
		var osmGeocoder = new L.Control.OSMGeocoder({placeholder: 'Search location...'});
		// The line above creates the search function for locating places.
		map.on('dblclick', onMapClick); // Here I am specifying the handler for the double-click event.
   </body>`Preformatted text`

I am aware that global variables in javascript are a bad practice. Forgive me I am relatively new to javascript. I want to
solve the problem first. Textboxes are created by double-clicking. The handler code for double-clicking event is as follows:

<script language="javascript">
   function onMapClick(e) {
	   var order_box = '<input type="text" id= ' + '"' + counter + '"' + ' onchange="doSubmit(' + "'" + counter + "'" + ')"' + ' size = "5">';
	   // I have also tried oninput and onblur
	   var myIcon = new L.divIcon({
	   var marker = new L.marker(e.latlng, {icon: myIcon}).addTo(map);
	    coordinates[counter] = e.latlng;
		str = JSON.stringify(coordinates);
		document.getElementById('coord1').value = str;

I have a counter variable that keeps track of the number of textboxes created. Since I can’t know how many textboxes
will be created before hand, I use the string version of the current value of the counter variable for the id of a
textbox just created. I have specified an onchange event on each textbox created that triggers its handler passing
the id of the textbox as an argument. The code for the handler is as follows:

function doSubmit(id_string) {
        alert("id_string: " + id_string);
		alert("type of id_string: " + typeof(id_string));
		coords = document.getElementById('coord1').value;
		coords_array = coords.split("},");
		var customer_order_size = document.getElementById(id_string).value;
		alert("textbox_id: " + document.getElementById(id_string).id);
		alert("customer_order_size: " + customer_order_size);
		var current_element = (coords_array[parseInt(id_string)]).split(":{");
		if(typeof(customer_order_size) != "undefined") {
			var complete_entry = customer_order_size + ":" + current_element[1];
			customer_orders[id_string] = complete_entry;

The problem now is that after I enter a value in the textbox and trigger the doSumbit by removing the focus from the textbox,
the document.getElementById(id_string).value is returning undefined. I have confirmed that the id is being passed correctly to
the doSubmit function and that the element exists. I have replaced onchange with onblur and oninput to no avail. I have searched
high and low, even as far as W3C Document Object Model (DOM) Level 2 Events Specification, also to no avail. I would be grateful
for pointers to what I might be doing wrong. Tested the code with Mozilla Firefox and Chrome, same result. Thanks for the anticipated help.

You… may possibly be getting tripped up by the HTML4 definition of ID, which requires a letter to start the ID with?

S’the only thing that immediately presents to mind. Try sticking a letter in there before the number.

var order_box = '<input type="text" id="o' + counter + '" onchange="doSubmit(' + "'o" + counter + "'" + ')"' + ' size = "5">';

EDIT: Also that extra space is bothering me.

Thank you very much @m_hutley for your suggestion. Will try it out. Sorry please…what extra space??

@m_hutley The one after id= right??

Yeah. I don’t THINK it’s a problem, but it might be.

Try copying the line I have in post #2 and see how it goes.

@m_hutley you were absolutely right!!! That was the problem!!! Thank you so much!!! iam grateful!! I have been painfully struggling with this for weeks now. So I really really appreciate…but now that that turned out to be the problem, it has created something of a riddle for me. I am hoping you might be able to sort it out. Before now in another scenario, using document.getElementById().value with the counter values worked just fine. Specifically if was ready to submit the map (cos the map is acting like a form) and clicked the submit button (I was using jquery to listen for a button clicked event) I could retrieve the textbox values properly with the way things were before incorporating your suggestion. It’s just I needed to rework the app to take advantage of the searchbox in such a way that I needed to make use of the textbox values before submission. That was when the returning “undefined” problem started. Do you have any ideas why my approach would work after submission but not work before submission? Many thanks again.

Only thing I could imagine at that point is that you were referring to the values before they existed, but without seeing the code it would be difficult to evaluate why something works at time X and not at time Y.

Okay …I think I have bothered you enough for one day. I really appreciate the help. Cheers!!!

1 Like