+1 vote
by (240 points)

I creating from custom JS widget input textbox with datalist.  In this macros creates button.
Button have global "window" function on click.
In function I need get all value from all input elements and send value to another function (where data will be sorting to correct saved data).

But after clicking on button nothing happen. All storage has old data and displayed form will be reset.


Used function:

	window.getEmpls = function(){
		var nm = State.passage;
		var bnam = document.getElementById('boss').value;
		addToLog('Boss value ', bnam);
		var n = $('emls').length;			
		for (var i = 0; i < n; i++){
			var id = 'emls' + i;
			var enma = document.getElementById(id).value;
			eSet(enma, nm.substring(0,nm.indexOf('Cfg')));
		}
	};

 

Macros created form (example):

<form>
<p><input list="employes" type="text" id="boss" name="boss" placeholder="Choice boss" value="" tabindex="0"></p>
<p><input list="employes" class="emls" type="text" name="empl" id="empl0" placeholder="Choice employer" value="" tabindex="0"></p>
<p> <button type="submit" onclick="window.getEmpls()" tabindex="0">Confirm</button> </p>
</form>

 

What I do wrong?

1 Answer

+2 votes
by (8.6k points)
selected by
 
Best answer

There are several issues in your code in respect to the HTML structure. First, this:

var n = $('emls').length;

It's not clear here whether "emls" should be a class name or an ID, and thus jQuery doesn't guess and simply uses it as an element name. Your HTML doesn't have any <emls> elements, so this doesn't find any. For all elemens with a class name "emls", you should instead use:
 

var n = $('.emls').length;

However, in the following loop you're looking for elements by ID using the following ID code:

var id = 'emls' + i;

... but your HTML doesn't have any elements with such IDs ("emls0", "emls1" and so on). It only has an element with the ID "boss" and another one with the ID "empl0". This is most likely a type and should be ...

var id = 'empl' + i;

Finally, I'd rewrite the whole loop a bit:

Array.from(document.getElementsByClassName("emls"))
	.forEach(function(el) {
		eSet(el.value, nm.substring(0, nm.indexOf('Cfg')));
	});

This has the benefit that you don't need to care about the specific IDs of those elements.

by (240 points)
Sorry for IDs. I forget update code when added his.

And very big thanks for loop code. You my lifesaver.=)
...