jQuery 如果为空,如何发布空的 <select .. multiple> HTML 元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1132303/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 10:43:43  来源:igfitidea点击:

How to POST empty <select .. multiple> HTML elements if empty?

jqueryhtmlmulti-selecthtml-select

提问by Vincent

I have the following multi-select box in a HTML form, where user can select one or more option.

我在 HTML 表单中有以下多选框,用户可以在其中选择一个或多个选项。

<select id="eng_0" name="eng_0[]" multiple size="3">
  <option value="Privilégier">Privilégier</option>
  <option value="Accepté">Accepté</option>
  <option value="Temporaire">Temporaire</option>
</select>

When the user selects no option, the form is POSTed to a PHP backend but it creates no empty array value for $_POST['eng_0'] as if the field was not even on the form.

当用户不选择任何选项时,表单将被 POST 到 PHP 后端,但它不会为 $_POST['eng_0'] 创建空数组值,就好像该字段甚至不在表单上一样。

This is kind of like the unchecked checkbox that is not submitted problem.

这有点像未提交的未选中复选框问题。

Is there any way to have it POST the select object even if there is no selected option? It can be in jQuery if that helps.

即使没有选择的选项,有没有办法让它 POST 选择对象?如果有帮助,它可以在 jQuery 中。

回答by Edward Dale

If your form is generated dynamically, you could include a hidden form element with the same name that contains a dummy value. Then, just ignore the dummy value, if the value you get for that variable is ['dummy_value']then you can treat that as meaning "nothing selected" in your code.

如果您的表单是动态生成的,您可以包含一个包含虚拟值的同名隐藏表单元素。然后,只需忽略虚拟值,如果您为该变量获得的值是,['dummy_value']那么您可以将其视为代码中“未选择任何内容”。

回答by Matt Bridges

Is there a reason you can't treat the situation where the array isn't set as if it was sent with no contents?

是否有理由不能将未设置数组的情况视为发送时没有内容?

if (!isset($_POST['eng_0']))
    $_POST['eng_0'] = array();

EDIT:

编辑:

Add a hidden field whenever the multiple select is present in your form:

只要表单中存在多项选择,就添加一个隐藏字段:

<input type="hidden" name="eng_0_exists" value="1"/>

Then check:

然后检查:

if (!isset($_POST['eng_0']) && isset($_POST['eng_0_exists']))
    $_POST['eng_0'] = array();

回答by Flame

If you add a hidden input beforethe multiple select element, it will send the hidden input value if none of the multiple select items have been selected. As soon as you select an option though, that selected value is used instead.

如果在多选元素之前添加隐藏输入,如果没有选择多选项目,它将发送隐藏输入值。但是,只要您选择一个选项,就会使用该选定值。

This way I was able to distinguish 2 different scenarios in Laravel/php, being:

这样我就能够在 Laravel/php 中区分两种不同的场景,分别是:

  • Set all myitemsto empty (requiring the hidden input, so PHP receives an empty string for myitems)
  • Update other properties of the model without touching myitems(so excluding any myitemsinput form the form. PHP will not receive the myitemskey)
  • 全部设置myitems为空(需要隐藏输入,所以 PHP 收到一个空字符串myitems
  • 无需触摸即可更新模型的其他属性myitems(因此不包括myitems表单中的任何输入。PHP 将不会收到myitems密钥)

Sample code:

示例代码:

<input type="hidden" name="myitems" value="" />
<select name="myitems[]" multiple>
  <option value="1">Foo</option>
  <option value="2">Bar</option>
</select>

回答by Stefan

Add something like

添加类似的东西

    $("#field").change(function() {
      if (($("#field").val() || []) == "") $("form").append("<input type='hidden' name='field' value=''>");
    });

回答by markus

You can add a - please select - entry and preselect it.

您可以添加一个 - 请选择 - 条目并预选它。

<select id="eng_0" name="eng_0[]" multiple size="3">
  <option value="nothing" selected="selected">- please select -</option>
  <option value="Privilégier">Privilégier</option>
  <option value="Accepté">Accepté</option>
  <option value="Temporaire">Temporaire</option>
</select>

回答by SparK

what if even when the user selects it, nothing about the select arrives in the $_POST?

如果即使用户选择了它,在 $_POST 中也没有关于选择的任何信息怎么办?

            <form action="cart.php" method="POST">
                <input type="hidden" id="acao" name="acao" value="add" />
                <input type="hidden" id="id" name="id" value="<?=$cnt->cnt_codigo?>" />
                <?php
                    $resOpc = mysql_query("SELECT * FROM loja_opcionais ORDER BY descricao")or die(mysql_error());
                    if(mysql_num_rows($resOpc) > 0){
                ?>
                <select id="opcional" nome="opcional">
                    <?php
                        while($opc = mysql_fetch_object($resOpc)){
                    ?>
                    <option value="<?=$opc->descricao?>"><?=$opc->descricao?></option>
                    <?php
                        }
                    ?>
                </select>
                <?php
                    }
                ?>
                <button class="botao" type="submit">Adicionar ao Carrinho</button>
            </form>

When I do print_r($_POST); on the other side the output is simply: Array ( [acao] => add [id] => 3 ) and no sign of the select tag, even when I change the value on the other side;

当我做 print_r($_POST); 另一方面,输出很简单: Array ( [acao] => add [id] => 3 ) 并且没有选择标记的符号,即使我更改了另一侧的值;

回答by Dirk Zaal

if there is no $_POST, Post an empty string (nothing) is absolutely the most simple solution.

如果没有$_POST,Post一个空字符串(什么都没有)绝对是最简单的解决方案。

Here my solution for a Form with a <select name="related[]" multiple>

这是我对带有一个表单的解决方案 <select name="related[]" multiple>

just add the following line in the php section that handles the storing of your form:

只需在处理表单存储的 php 部分添加以下行:

if (!isset($_POST['related'])) $_POST['related']="";

回答by Esko Piirainen

Include <input type="hidden" name="yourfield" value="" />to your form where the name is the same as for your multiple="multiple"select.

包括<input type="hidden" name="yourfield" value="" />到您的表单中,其中名称与您multiple="multiple"选择的名称相同。



It is unfortunate that browsers do not send empty form parameters for multiple="multiple"selects like they do for non-multiple selects or a normal inputs.

不幸的是,浏览器不会multiple="multiple"像非多选或普通输入那样为选择发送空表单参数。

Using a dummy value as proposed in the accepted answer is not a very clean solution.

使用已接受答案中提出的虚拟值并不是一个非常干净的解决方案。

(This question has nothing to do with jQuery)

(这个问题与jQuery无关)