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:
- Where is my gap in jQuery understanding such that I attempted to chain
find()toval() - How would I accomplish my requirement: I want to clear all inputs and toggle required on those with class
.required.
Thank you!
The issue is not with the chaining, but your repeated use of
find().The first
find()retrieves all:inputelements and clears their value, which is fine. However the secondfind()is then searching inside all thoseinputelements for.required. This cannot be valid asinputcannot have child elements (exceptselect, 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 usefilter()instead: