How can I filter using the current value of a text box in a jQuery selector?

Posted by spudly on Stack Overflow See other posts from Stack Overflow or by spudly
Published on 2010-04-02T12:44:49Z Indexed on 2010/04/02 12:53 UTC
Read the original article Hit count: 140

Filed under:
|
|
|
|

I have a validation script that checks for data-* attributes to determine which fields are required. If an element has the 'data-required-if' attribute (which has a jQuery selector as it's value), it checks to see if any elements are found that match that selector. If any are found, the field is required. It does something similar to the following:

$('[data-required-if]').each(function () {
  var selector = $(this).attr('data-required-if'),
      required = false;

  if ( !$(selector).length ) {
    required = true;
    // do something if this element is empty
  }
});

This works great, but there's a problem. When you use the attribute selector to filter based on the current value of a text field, it really filters on the initial value of the text field.

<input
  type='text'
  id='myinput'
  value='initial text'
/>

<input
  type='text'
  id='dependent_input'
  value=''
  data-required-if="#myinput[value='']"
/>

// Step 1: type "foobar" in #myinput
// Step 2: run these lines of code:
<script>
  $('#myinput').val()                  //=> returns "foobar"
  $('#myinput[value="foobar"]').length //=> returns 0
</script>

I understand why it's doing that. jQuery probably uses getAttribute() in the background. Is there any other way to filter based on the current value of an input box using purely jQuery selectors?

© Stack Overflow or respective owner

Related posts about jQuery

Related posts about selector