Welcome to the nuBuilder Forums!

Join our community by registering and logging in.
As a member, you'll get access to exclusive forums, resources, and content available only to registered users.

How to make fields move up automatically when another field is hidden?

Questions related to using nuBuilder Forte.
Post Reply
yvesf
Posts: 348
Joined: Sun Mar 14, 2021 8:48 am
Location: Geneva
Has thanked: 94 times
Been thanked: 12 times

How to make fields move up automatically when another field is hidden?

Post by yvesf »

Hi everyone,

In my nuBuilder form, I hide certain fields dynamically using JavaScript (for example, nuHide('fieldID')).
However, when a field is hidden, the other fields below it stay in the same position — leaving an empty gap.

Is there a way to make the following fields automatically “move up” to fill that space, similar to how elements flow in standard HTML layouts?

Ideally, I’d like to avoid manually repositioning each field if possible.
If it requires JavaScript or a specific layout technique (like subforms or div sections), I’d really appreciate some guidance or examples.

Thanks in advance!

Yves
kev1n
nuBuilder Team
Posts: 4581
Joined: Sun Oct 14, 2018 6:43 pm
Has thanked: 76 times
Been thanked: 536 times
Contact:

Re: How to make fields move up automatically when another field is hidden?

Post by kev1n »

Hi,

Try the function below

Code: Select all


/**
 * Rearrange visible objects vertically when some are hidden.
 * 
 * Usage:
 *   nuHide('fieldID');
 *   rearrangeObjects(); // call this after hiding or showing fields
 */

// Example: Call myHide() for an object you'd like to hide:

function myHide(id) {
  nuHide(id);
  rearrangeObjects(); // call this after hiding or showing fields
}

function rearrangeObjects() {

	// Clone the original object list from nuSERVERRESPONSE
	const responseObjects = {
		objects: [...nuSERVERRESPONSE.objects]
	};

	let lastTop = null;   // bottom of previous visible element
	let spacing = 6;      // default vertical spacing between stacked fields

	for (const obj of responseObjects.objects) {

		const $el = $('#' + obj.id);
		if ($el.length === 0) continue;

		// Skip hidden fields
		if (!$el.is(':visible')) continue;

		// Read original position info
		const origTop    = parseInt(obj.top, 10);
		const origLeft   = parseInt(obj.left, 10);
        const height = nuTotalHeight(obj.id);

		let newTop;

		if (lastTop === null) {
			// First visible field stays at its original top
			newTop = origTop;
		} else {
			// Move right below the previous visible field
			newTop = lastTop + spacing;
		}

		// Apply new position to field
		$el.css({
			position: 'absolute',
			top: newTop + 'px',
			left: origLeft + 'px'
		});

		// Reposition label
		const $label = $('#label_' + obj.id);
		if ($label === 0) continue;
		nuSetLabelText(obj.id, $label.html());

		// Update the lastTop for next visible element
		lastTop = newTop + height;
	}
}
Post Reply