jQuery selector does not find itself

Asked

Viewed 29 times

1

I was assembling a feature that aimed to find others selects of equal 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>
<select name="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 cannot find it.

What is the need to find this select?

  • Try 'select[name^="group"] option[value='+this.value+']' remember that you are trying to access a select child object which is the option...

1 answer

1


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

For this selector to work it needed the HTML of <select> had value="xxx", and Javascript would already work with:

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

(Example: https://jsfiddle.net/u1vyr6ae/2/)

To do what you’re looking for 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: https://jsfiddle.net/u1vyr6ae/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.