使用 HTMX 更新选择更改时的表单字段

问题描述 投票:0回答:1

在我的其中一个页面中,我有一个

select
元素和一个
form
。我想要实现的是当
select
更改时更新表单中的字段值,这成功发生了。我做了很多测试并多次阅读了htmx.org上的文档,直到我得到这个,但即使现在我也不明白为什么我的配置有效。这是一个错误吗?它是正确的?我一点也不确定,尤其是当我使用
hx-target="#title,#slug,#shortcode"
hx-target="#shortcode"
都获得相同的良好结果时,主要的一个至少是
hx-target
中包含的三个目标 id 之一,否则
替换表单字段时,select
将被删除。你觉得怎么样?

<select id="select-settings" name="select-settings" hx-get="/get-settings" hx-target="#title,#slug,#shortcode">
    <option value="">-- Select Settings --</option>
    <option value="super-opt10ns">Dolor qui voluptatem</option>
</select>

<form id="field-form" action="options.php" method="post">
    <input type="text" id="title" name="title" value="">
    <input type="text" id="slug" name="slug" value="">
    <input type="text" id="shortcode" name="shortcode" value="">
</form>

来自 /get-settings 端点的响应:

<input type="text" hx-swap-oob="outerHTML:#title" id="title" name="title" value="Dolor qui voluptatem">
<input type="text" hx-swap-oob="outerHTML:#slug" id="slug" name="slug" value="super-opt10ns">
<input type="text" hx-swap-oob="outerHTML:#shortcode" id="shortcode" name="shortcode" value="[form slug='test']">
htmx
1个回答
0
投票

两个

hx-target
值都起作用的原因是响应为每个输入定义了带外交换。请记住,带外交换会替换 DOM 中由
id
属性找到的元素。

使用这种更简单的方法您应该得到相同的结果:

<select id="select-settings" name="select-settings" hx-get="/get-settings" hx-target="#field-form">
    <option value="">-- Select Settings --</option>
    <option value="super-opt10ns">Dolor qui voluptatem</option>
</select>

<form id="field-form" action="options.php" method="post">
    <input type="text" id="title" name="title" value="">
    <input type="text" id="slug" name="slug" value="">
    <input type="text" id="shortcode" name="shortcode" value="">
</form>

响应也可以简化:

<input type="text" id="title" name="title" value="Dolor qui voluptatem">
<input type="text" id="slug" name="slug" value="super-opt10ns">
<input type="text" id="shortcode" name="shortcode" value="[form slug='test']">

只是因为您问:使用 HTMX 没有唯一正确的方法。方法可以有很多种。但如果您打算从 HTTP 响应更新表单值,这绝对有效。

© www.soinside.com 2019 - 2024. All rights reserved.