Select input text for its value

2

I would like to select an input type text field that contains the word "hi" in it.

Assuming my input is this:

<input type='text' id='texto' />

I saw that it is possible through:

$("#texto[value='oi']")

But I saw that it only works if the value is explicit in the "value" attribute. It does not happen most of the time.

Is there any other selector for me to achieve this without having to set the value attribute of the input?

    
asked by anonymous 06.04.2015 / 15:45

2 answers

4

Can not do this. The selectors act similarly to CSS, on elements and attributes that are in the DOM.

You will have to select the elements you want manually, as indicated in this answer in SOEN :

var inputsEscritoOi = $('input').filter(function() {
    return $(this).val().indexOf('oi');
});

If you want some ease in using this, you can even create a jQuery plug-in:

$(function() {
  $("#colorir").on("click", function() {
    $("input").valContain("oi").css({
      color: "red"
    });
  });
});

(function($) {
    $.fn.valContain = function(str) {
      return this.filter(function() {
        return $(this).val().indexOf(str) >= 0;
      });
    };
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="text" />
<input type="text" />
<input type="text" />
<input type="text" />
<button id="colorir">colorir</button>
    
06.04.2015 / 16:42
0

You can loop through the input[type="text"] by checking that the value is "hi".

$('input[type="text"]').each(function(e){
    if($(this).val() == 'oi'){
       // faz algo
    }
});

$(function(){
    $('#selecionar').on('click', function(){
        $('input[type="text"]').each(function(e){
            if($(this).val() == 'oi'){
                $(this).toggleClass('selecionado');
            }
        });
    });
});
.selecionado{border-color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>

<input type='text' value='foo'/>
<input type='text' value='bar'/>
<input type='text' value='oi'/>
<input type='text' value='baz'/>

<button id='selecionar'>Selecionar 'oi'</button>
    
06.04.2015 / 16:41