lapinkoira lapinkoira - 3 years ago 149
jQuery Question

Unify :contains query and input[value*=''] within the same query

I have two different queries I would like to unify them in a single query. One is a query which tracks an HTML element which contains a word as text:

var component = ".component";
$(component).find(".search-here:contains('test')");

<tr class="search-here">
<td>test</td>
</tr>


Other one is a query which tracks the inputs of a form and checks the text value of them:

var component = "#form";
$(component).find("input[type='text']:input[value*='test']").closest('.search-here');

<div class="search-here">
<input type="text" value="test, test1, test2">
</div>


Both of them, form or any HTMl component have the value I want to track wrapped by a .search-here class

The issue here is I cant track the inputs of a form with :contains because they dont have a text value, they have an attribute called "value"

Having two different queries is a bit messy and tricky, would it be possible to do it in a single generic query without having to modify the form which can query "text" word being a value property or a text value?

Answer Source

Try something like $(component).filter("[type='text'],[value*='test'],:contains('test')").closest('.search-here')

As long as the input has a type = text or a value with test in it, it will return.

Demo

var component = ".search-here *";
var s = $(component).filter("[type='text'],[value*='test'],:contains('test')").closest('.search-here');

console.log($(s).length)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form">
  <div class="search-here">
    <input type="text" value="test, test1, test2">
  </div>
  <div class="search-here">
  <input type="number" value="run"/>
  </div>
</form>

<table>
  <tr class="search-here">
    <td>test</td>
  </tr>
</table>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download