Select2 不创建名称属性

tes*_*ter 5 php tags jquery post jquery-select2

使用 select2 jQuery PlugIn 我创建了一个标签框。因此我使用了以下 html 表单代码:

<form action="someAction" method="post">
    <fieldset>
        <select id="tags" multiple="" name="tags">
            <option value="tag1">val1</option>
            <option value="tag2">val2</option>
            <option value="tag3">val3</option>
        </select>
        <button type="submit" class="btn">Submit</button>
    </fieldset>
</form>
Run Code Online (Sandbox Code Playgroud)

Select2 从中生成以下字段:

<input type="text" class="select2-input" autocomplete="off" id="s2id_autogen1" style="width: 10px;">
Run Code Online (Sandbox Code Playgroud)

问题name在于缺少该属性。$_POST如果没有name属性,如何从 PHP中的变量中获取输入字段的数据/文本?我该如何管理?

设置JS如下:

$(document).ready(function() {
$("#tags").select2({
    placeholder: "Insert tag",
    allowClear: true,
    minimumInputLength: 2,
    maximumSelectionSize: 1,
    minimumWidth: 200
});
Run Code Online (Sandbox Code Playgroud)

});

Her*_*amo 0

POST 需要名称才能工作,但我注意到它有一个 id:

id="s2id_autogen1"
Run Code Online (Sandbox Code Playgroud)

使用JS通过id抓取值并post出来。

如果 id 不断变化,您可以使用该类:

HTML:

<form action="someAction" method="post">
<fieldset>
    <!-- This will contain the value from the generated input -->
    <input type = 'hidden' name = 'myField' id = 'myField' />
    <select id="tags" multiple="" name="tags">
        <option value="tag1">val1</option>
        <option value="tag2">val2</option>
        <option value="tag3">val3</option>
    </select>
    <button type="submit" class="btn">Submit</button>
</fieldset>
Run Code Online (Sandbox Code Playgroud)

JS

$(document).ready(function(){
       $("#tags").select2({
       placeholder: "Insert tag",
       allowClear: true,
       minimumInputLength: 2,
       maximumSelectionSize: 1,
       minimumWidth: 200
});

//Make it so everytime the input with the class select2-input value is changed
//the value gets copied into the element with the id myField
$('input.select2-input').live('change', function(){
    $('input#myField').val($(this).val());
});
Run Code Online (Sandbox Code Playgroud)

});

像这样提交表单将自动包含 POST 变量的值。