javascriptjqueryjquery-chaining

Chaining find() to val()


Is there a way to chain find() following val()?

For example, given the following code, I would like to clear the values of all the inputs but only toggle the required property of the inputs that have a class of .required:

$('#some-selector')
    .find(':input')
    .val('')
    .find('.required')
    .prop('required', someBoolean);

From the jQuery docs, it is apparent that val() returns a string, number or array. Seems to me that find() will not function on this return value as I believe it needs a jQuery object.

So a few questions:

  1. Where is my gap in jQuery understanding such that I attempted to chain find() to val()
  2. How would I accomplish my requirement: I want to clear all inputs and toggle required on those with class .required.

Thank you!


Solution

  • The issue is not with the chaining, but your repeated use of find().

    The first find() retrieves all :input elements and clears their value, which is fine. However the second find() is then searching inside all those input elements for .required. This cannot be valid as input cannot have child elements (except select, but that's not applicable in this case).

    You instead need to search within the current collection for elements with the class of required. To do that use filter() instead:

    $('#some-selector')
      .find(':input').val('')
      .filter('.required').prop('required', someBoolean);