D
D
Dmitry Belyaev2016-05-27 06:20:14
JavaScript
Dmitry Belyaev, 2016-05-27 06:20:14

How to determine that the select2 plugin is connected to the element and correctly change its value?

Good day to all!
I am writing an extension for autofilling forms on websites, I ran into a problem on a site that uses the select2 plugin, the change in the value of the element is not visually displayed, and when submitting the form, the data filled in by the plugin goes into the request every other time (to be precise, I have (Chrome 50/Ubuntu 14.04) everything is sent, the customer (Chrome 50/Windows 8) does not).
I came to the idea that you need to manage such form elements through the plugin itself.
I have a link to a native (not jQuery) domNode, on which the plugin is initialized, in the case of the site being tested, this is , which turns out to be hidden thanks to select2 Actually, the questions arose: Is it possible to determine from an element that select2 is connected to it?<select>

How to correctly change the value of this element?
What to do if jQuery is not in the global object (it lies in the closure of the site code)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Zuev, 2016-05-27
@yurzui

Is it possible to determine from an element that select2 is connected to it?

Probably you can
var elem = document.querySelector('select');

console.log(!!$.data(elem).select2);
console.log(elem.className === 'select2-hidden-accessible');
console.log(elem.nextElementSibling.className.indexOf('select2') === 0);

Maybe you need to trigger changes
// change value
// 1. jquery methos
$(elem).val('WY').trigger('change');

// 2. native
elem.value = 'WY'
if ("createEvent" in document) {
  var evt = document.createEvent("HTMLEvents");
  evt.initEvent("change", false, true);
  elem.dispatchEvent(evt);
}
else {
  elem.fireEvent("onchange");
}

Example here jsfiddle.net/yurzui/n073jveu/
What to do if jQuery is not in the global object (it lies in the closure of the site code)?
According to the circumstances) Can load then. Is jQuery required?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question