views:

28

answers:

3

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?

A: 

Well you could write a "change" handler for the "myinput" field that stashes the value on some other attribute, and then write your selector to use that.

I put a demo/test page out at http://gutfullofbeer.net/foobar.html so you can see if that might solve your problem.

<script>
  $(function() {
    $('#clickee').click(function() {
      $('#count').text('' + $('#txt[bar=foo]').length);
    });
    $('#txt').change(function() {
      $(this).attr('bar', $(this).val());
    });
  });
</script>

...

<body>
  <input type='text' id='txt'>
  <button id='clickee'>click</button>

  <span id='count></span>
</body>
Pointy
A: 
Andrey Tagaew
A: 

Another option you have is creating a selector, like this:

jQuery.expr[':'].hasValue = function(a){ return $(a).val() !== ""; };

Then you can use it like this:

$('#myinput:hasValue').length  //"1" if anything is typed in there
Nick Craver