jQuery selector does not find itself

1

I was putting together a feature that was meant to find other selects with same value when I came across this situation:

jQuery('select[name="group2"]').val('emissao');

jQuery('select[name^="group"]').on('change', function(){
  console.log(this.value);
  var o = null;
  console.log(o = jQuery('select[name^="group"][value="'+this.value+'"]'));
  console.log(o['selector']);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><selectname="group1">
  <option value=""></option>
  <option value="emissao">Data Emissao</option>
  <option value="entrada">Data Entrada</option>
</select>

<select name="group2">
  <option value=""></option>
  <option value="emissao">Data Emissao</option>
  <option value="entrada">Data Entrada</option>
</select>

Note that it already has the new value yet the selector does not find it.

What is the precedence for finding this select ?

    
asked by anonymous 16.03.2016 / 14:22

1 answer

1

The problem here is that you are looking for value in attributes. There is a difference between what is in the attributes (which can be said to be HTML, in this case the original version) and the .value property that is dynamic and is changing. That is difference between the HTML and its representation in JavaScript DOM.

For this selector to work it was necessary to have the HTML of <select> ter value="xxx" , and JavaScript would already work with:

var el = jQuery('select[name^="group"][value="emissao"]');

(Example: link )

To do what you want, you can use it like this:

jQuery('select[name^="group"]').on('change', function() {
    var self = this;
    var selects = jQuery('select[name^="group"]').filter(function() {
        return this.value == self.value;
    });
    console.log(selects.length); // 2 quando os valores forem iguais
});

jsFiddle: link

    
19.04.2016 / 23:34