PageSourceSearch

https://elco-pro.com/local/components/prodvigaeff/dadata.location/js/jquery-dadata.js?178357717312575

js elco-pro.com collected 2026-10-06 17:43:01 UTC 12,575 bytes, 451 lines download raw bytes

1(function($)
2{
3	var repo = [], _default = {
4		token: null,
5		inputName: 'UF_LOCATION',
6		required: false,
7		uselocation: false
8	};
9
10	var methods = {
11		init: function(options)
12		{
13			return this.each(function()
14			{
15				var container = $(this);
16				container.data('DaData', new Module(options, container));
17			});
18		},
19		getCitySuggestions: function()
20		{
21			return this.data('DaData').city;
22		}
23	};
24
25	var Module = function(options, container)
26	{
27		this.options = $.extend({}, _default, options);
28		this.container = container;
29		this.country = null;
30		this.region = null;
31		this.city = null;
32
33		this.prepareParams();
34		this.init();
35	};
36
37	Module.prototype.prepareParams = function()
38	{
39		this.country = this.container.find('[data-dadata-country]');
40
41		if(this.options.countryInput && this.options.countryInput.length > 0)
42		{
43			if($("#" + this.options.countryInput).length)
44			{
45				this.country = $("#" + this.options.countryInput);
46			}
47		}
48		this.region = this.container.find('[data-dadata="region"]');
49		this.city = this.container.find('[data-dadata="city"]');
50		this.address = this.container.find('[name="ADDRESS"]');
51		if(!this.country || this.country.length === 0)
52		{
53			$.error('jQuery-DaData: input "country" not found');
54		}
55		if(!this.region || this.region.length === 0)
56		{
57			$.error('jQuery-DaData: input "region" not found');
58		}
59
60		if(!this.options.token)
61		{
62			$.error('jQuery-DaData: options token not defined');
63		}
64	};
65
66	Module.prototype.init = function()
67	{
68		var self = this;
69
70		const { createSuggestions } = window.Dadata;
71
72		if(self.country.attr('data-dadata') == "country")
73		{
74			//let oldValueCountry = self.country.val();
75			self.countrySuggestions = createSuggestions(self.country[0], {
76				token: this.options.token,
77				type: "country",
78				params: {
79					from_bound: { value: 'country' },
80					to_bound: { value: 'country' }
81				},
82				onSelect: function(suggestion, changed)
83				{
84					self.country.blur();
85					const oldValue = self.country.attr('data-dadata-country');
86					let dadataValue = suggestion.value;
87					self.country.attr('data-dadata-country', dadataValue);
88					self.country.val(dadataValue);
89
90					// Проверяем, изменилось ли значение относительно ввода пользователя
91					let reallyChanged = oldValue !== dadataValue;
92					if(reallyChanged)
93					{
94						self.regionSuggestions.setOptions({
95							params: {
96								locations: [{
97									country: self.country.attr('data-dadata-country')
98								}]
99							},
100							geolocation: false,
101							restrict_value: true
102						});
103						/*if(this.address)
104						{
105							var address = createSuggestions(this.address[0], {
106								token: this.options.token,
107								type: 'address'
108							});
109							if(address)
110							{
111								address.clear();
112								address.setOptions({
113									params: {
114										locations: {
115											//country: suggestion.data.country,
116											country: this.country.attr('data-dadata-country')
117										}
118									},
119									restrict_value: true
120								});
121							}
122						}*/
123						self.clearNoValidRegion();
124					}
125				},
126				onSelectNothing: function()
127				{
128					self.clearNoValidCountry();
129				},
130				formatResult: function(value, currentValue, suggestion, options)
131				{
132					var replacesValue = value.replace(currentValue,'<mark>'+currentValue+'</mark>');
133					var v = '<span class="dadata-element-wrapper dropdown-select__item">' +
134						'<span class="dropdown-select__item-main">'+replacesValue+'</span>' +
135						'</span>';
136					return v;
137				},
138			});
139
140			// Дополнительный обработчик на потерю фокуса для всех остальных случаев
141			$(self.country[0]).on('blur', async function()
142			{
143				const inputValue = $(this).val().trim();
144				const module = self;
145				if (!inputValue)
146				{
147					module.clearNoValidCountry();
148					return;
149				}
150
151				// Проверяем, есть ли выбранная подсказка
152				const selected = self.countrySuggestions.getSelection();
153				if (selected) return;
154
155				// Проверяем, были ли вообще подсказки для этого значения
156				try {
157					const suggestions = await self.countrySuggestions.getSuggestions();
158					if (!suggestions || suggestions.length === 0)
159					{
160						console.log('Подсказок не найдено');
161						module.clearNoValidCountry();
162					}
163				}
164				catch (error)
165				{
166					console.error('Ошибка при проверке подсказок:', error);
167				}
168			});
169			/*if(self.options.uselocation)
170			{
171				var countrySg = createSuggestions(self.country[0], {
172					token: this.options.token,
173					type: 'address'
174				});
175				countrySg.setOptions({
176					onSearchStart: function(q)
177					{
178						q.uselocation = true;
179					}
180				});
181			}*/
182		}
183
184		if(self.region.attr('data-dadata') == "region")
185		{
186			console.log(self.country.attr('data-dadata-country'));
187			self.regionSuggestions = createSuggestions(self.region[0], {
188				params: {
189					locations: [{
190						country: self.country.attr('data-dadata-country')
191					}],
192					from_bound: { value: 'region' },
193					to_bound: { value: 'region' }
194				},
195				token: this.options.token,
196				type: 'address',
197				hint: false,
198				formatSelected: function(suggestion)
199				{
200					if(self.city.length)
201					{
202						/*sgt.setOptions({
203							params: {
204								locations: {
205									region: suggestion.data.region,
206									country: self.country.attr('data-dadata-country')
207								}
208							},
209							restrict_value: true
210						});*/
211					}
212					if(suggestion.data.region_type == "г")
213					{
214						return suggestion.data.region;
215					}
216					else
217					{
218						console.log(suggestion.data);
219						return suggestion.data.region_with_type;
220					}
221				},
222				onSelect: function(suggestion, changed)
223				{
224					self.region.blur();
225					const oldValue = self.region.attr('data-dadata-region');
226					let dadataValue = suggestion.value;
227					self.region.attr('data-dadata-region', dadataValue);
228					if(changed)
229					{
230						if(self.city.length)
231						{
232							// Проверяем, изменилось ли значение относительно ввода пользователя
233							let reallyChanged = oldValue !== dadataValue;
234
235							if(reallyChanged)
236							{
237								self.city.closest(".js-input-text").removeClass("is-focused");
238								self.citySuggestions.setOptions({
239									params: {
240										locations: [{
241											region: suggestion.data.region,
242											country: self.country.attr('data-dadata-country')
243										}],
244										from_bound: { value: 'city' },
245										to_bound: { value: 'settlement' },
246									},
247									geolocation: false,
248									restrict_value: true
249								});
250								self.clearNoValidCity();
251							}
252						}
253						else
254						{
255							self.container.find('input[name="' + self.options.inputName + '"]').val(suggestion.unrestricted_value);
256						}
257					}
258				},
259				onSelectNothing: function()
260				{
261					self.clearNoValidRegion();
262				},
263				formatResult: function(value, currentValue, suggestion, options)
264				{
265					var replacesValue = value.replace(currentValue,'<mark>'+currentValue+'</mark>');
266					var v = '<span class="dadata-element-wrapper dropdown-select__item">' +
267						'<span class="dropdown-select__item-main">'+replacesValue+'</span>' +
268						'</span>';
269
270					return v;
271				},
272			});
273
274			// Дополнительный обработчик на потерю фокуса для всех остальных случаев
275			$(self.region[0]).on('blur', async function()
276			{
277				const inputValue = $(this).val().trim();
278				const module = self;
279
280				if (!inputValue)
281				{
282					module.clearNoValidRegion();
283					return;
284				}
285
286				// Проверяем, есть ли выбранная подсказка
287				const selected = self.regionSuggestions.getSelection();
288				if (selected) return;
289
290				// Проверяем, были ли вообще подсказки для этого значения
291				try {
292					const suggestions = await self.regionSuggestions.getSuggestions();
293					if (!suggestions || suggestions.length === 0)
294					{
295						console.log('Подсказок не найдено');
296						console.log(suggestions);
297						module.clearNoValidRegion();
298					}
299				} catch (error) {
300					console.error('Ошибка при проверке подсказок:', error);
301				}
302			});
303		}
304
305		if(self.city.length)
306		{
307			self.citySuggestions = createSuggestions(self.city[0], {
308				token: this.options.token,
309				type: 'address',
310				geolocation: false,
311				params: {
312					from_bound: { value: 'city' },
313					to_bound: { value: 'settlement' },
314				},
315				hint: false,
316				formatSelected: function(suggestion)
317				{
318					return suggestion.data.settlement || suggestion.data.city;
319				},
320				onSelectNothing: function(query)
321				{
322					if(self.city.val() != query)
323					{
324						self.clearNoValidCity();
325					}
326				},
327				formatResult: function(value, currentValue, suggestion, options)
328				{
329					var replacesValue = value.replace(currentValue,'<mark>'+currentValue+'</mark>');
330					var v = '<span class="dadata-element-wrapper dropdown-select__item">' +
331						'<span class="dropdown-select__item-main">'+replacesValue+'</span>' +
332						'</span>';
333					return v;
334				},
335				onSelect: function(data, changed)
336				{
337					self.container.find('input[name="' + self.options.inputName + '"]').val(data.unrestr
337icted_value);
338					self.city.blur();
339				}
340			});
341
342			// Дополнительный обработчик на потерю фокуса для всех остальных случаев
343			$(self.city[0]).on('blur', async function()
344			{
345				const inputValue = $(this).val().trim();
346				const module = self;
347
348				// Если поле пустое - просто очищаем
349				if (!inputValue)
350				{
351					module.clearNoValidCity();
352					return;
353				}
354
355				// Проверяем, есть ли выбранная подсказка
356				const selected = self.citySuggestions.getSelection();
357				if (selected) return;
358
359				// Проверяем, были ли вообще подсказки для этого значения
360				try {
361					const suggestions = await self.citySuggestions.getSuggestions();
362					if (!suggestions || suggestions.length === 0)
363					{
364						console.log('Подсказок не найдено');
365						module.clearNoValidCity();
366					}
367				} catch (error) {
368					console.error('Ошибка при проверке подсказок:', error);
369				}
370			});
371			/*	if(self.options.uselocation)
372				{
373					var citySg = createSuggestions(self.city[0], {
374						token: this.options.token,
375						type: 'address'
376					});
377					citySg.setOptions({
378						onSearchStart: function(q)
379						{
380							q.uselocation = true;
381						}
382					});
383				}
384
385				var sgt = createSuggestions(self.city[0], {
386					token: this.options.token,
387					type: 'address'
388				});*/
389		};
390		/*if(self.options.uselocation)
391		{
392			var regionSg = createSuggestions(self.region[0], {
393				token: this.options.token,
394				type: 'address'
395			});
396			regionSg.setOptions({
397				onSearchStart: function(q)
398				{
399					q.uselocation = true;
400				}
401			});
402		}*/
403
404		//self.regionSuggestions.fixData($(self.region).attr('data-dadata-region'));
405	};
406
407	Module.prototype.clearNoValidCountry = function()
408	{
409		let self = this;
410		self.container.find('input[name="' + self.options.inputName + '"]').val('');
411		self.country.val("").closest(".js-input-text").removeClass("is-focused");
412		self.region.val("").closest(".js-input-text").removeClass("is-focused");
413
414		if(self.city.length)
415		{
416			self.city.val("").closest(".js-input-text").removeClass("is-focused");
417		}
418	};
419	Module.prototype.clearNoValidRegion = function()
420	{
421		let self = this;
422		self.container.find('input[name="' + self.options.inputName + '"]').val('');
423		self.region.val("").closest(".js-input-text").removeClass("is-focused");
424
425		if(self.city.length)
426		{
427			self.city.val("").closest(".js-input-text").removeClass("is-focused");
428		}
429	};
430	Module.prototype.clearNoValidCity = function()
431	{
432		let self = this;
433		self.city.val("").closest(".js-input-text").removeClass("is-focused");
434		self.container.find('input[name="' + self.options.inputName + '"]').val('');
435	};
436	$.fn.DaData = function(method)
437	{
438		if(methods[method])
439		{
440			return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
441		}
442		else if(typeof method === 'object' || !method)
443		{
444			return methods.init.apply(this, arguments);
445		}
446		else
447		{
448			$.error('Метод с именем ' + method + ' не существует для jQuery.DaData');
449		}
450	};
451})(jQuery);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.