简体   繁体   中英

How do I use JQuery to iterate a form from the bottom to the top, most nested element first without knowing the id of the deepest element beforehand?

I have a dynamic form builder that create a form in an MVC web application. It's arranged into sections and questions, sections contain questions or other sections.

The plan was to have some sections open based on the input of certain questions (so for instance checking a box saying you own a car makes the section on car details enabled). All sections which could be opened need to start disabled/hidden (so they can be opened on the relevant input).

All sections and questions have an id although unfortunately I won't know what these are until the page is loaded as Id's are generated dynamically, so i can't just start iterating up from a known deepest element, I have to find it first and then iterate..

I have no idea how to iterate through from the bottom up up, deepest first. If I iterate from top to bottom, any nested openable sections within openable won't get disabled as the parent will be deactivated before it can be.

Help would be VERY MUCH appreciated.

Thank you.

Did you take a look at JQuery's closest() function?

Example:

function openParent(jq_element) {
    jq_element.show();
    if(jq_element.parent().length) {
        openParent(jq_element.closest());
    }
}

$('input').each(function() {
    openParent($(this));
});

You could also try something with the parents() function, you can find the differences on the JQuery documentation pages:

.closest()

  • Begins with the current element
  • Travels up the DOM tree until it finds a match for the supplied
    selector
  • The returned jQuery object contains zero or one element for each element in the original set, in document order

.parents()

  • Begins with the parent element
  • Travels up the DOM tree to the document's root element, adding each ancestor element to a temporary collection; it then filters that collection based on a selector if one is supplied
  • The returned jQuery object contains zero or more elements for each element in the original set, in reverse document order

UPDATE

To find the most deepest element, you could iterate over all elements that don't have a child element (so all 'deepest' elements):

$('body *:not(:has("*"))');

If you need to open sections based on checkboxes that are checked or not (like your own a car example) You could do something like this:

$('input:checkbox:checked').each(function () {
    $(  '#' + $(this).data('referenced-section-id-from-current-element')  ).show();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM