开发者

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

开发者 https://www.devze.com 2022-12-25 17:14 出处:网络
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 开发者_如何学Pyth

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 开发者_如何学Pythonas 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?


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


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>


As an option you can add an attribute to all your input tags with default value.

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

Then, when you using selector, you should compare the actual value of input with its initialValue attribute

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号