Skip to content

Commit ff0de7b

Browse files
Copilotegil
andcommitted
Implement support for clicking submit button outside form with form attribute
Co-authored-by: egil <[email protected]>
1 parent fc32443 commit ff0de7b

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

src/bunit/EventDispatchExtensions/TriggerEventDispatchExtensions.cs

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,10 +176,62 @@ private static bool TryGetParentFormElementSpecialCase(
176176
IHtmlButtonElement { Type: "submit", Form: not null } button => button.Form,
177177
_ => null
178178
};
179+
180+
// If form is still null, try to find it by the form attribute for submit buttons/inputs
181+
if (form is null && element.HasAttribute("form"))
182+
{
183+
var isSubmitElement = element switch
184+
{
185+
IHtmlInputElement { Type: "submit" } => true,
186+
IHtmlButtonElement { Type: "submit" } => true,
187+
_ => false
188+
};
189+
190+
if (isSubmitElement)
191+
{
192+
var formId = element.GetAttribute("form");
193+
if (!string.IsNullOrEmpty(formId))
194+
{
195+
// Try to find the form element by traversing up to find a common ancestor
196+
// and then searching down for the form
197+
form = FindFormById(element, formId);
198+
}
199+
}
200+
}
179201

180202
return form is not null
181203
&& form.TryGetEventId(Htmlizer.ToBlazorAttribute("onsubmit"), out eventId);
182204
}
205+
206+
private static IHtmlFormElement? FindFormById(IElement element, string formId)
207+
{
208+
// First try the owner's GetElementById
209+
var formByOwner = element.Owner?.GetElementById(formId) as IHtmlFormElement;
210+
if (formByOwner is not null)
211+
{
212+
return formByOwner;
213+
}
214+
215+
// If that didn't work, traverse up to find a common ancestor and search its children
216+
// Start from the parent
217+
var current = element.Parent as IElement;
218+
while (current is not null)
219+
{
220+
// Search children of current element for the form
221+
foreach (var child in current.Children)
222+
{
223+
if ((child.Id == formId || child.GetAttribute("id") == formId) && child is IHtmlFormElement htmlForm)
224+
{
225+
return htmlForm;
226+
}
227+
}
228+
229+
// Move up to parent
230+
current = current.Parent as IElement;
231+
}
232+
233+
return null;
234+
}
183235

184236
private static bool EventIsDisabled(this IElement element, string eventName)
185237
{

0 commit comments

Comments
 (0)