dongyong5255 2015-07-27 13:41
浏览 114
已采纳

从列表中动态选择字段并将其添加到表单中

In a form I need to dynamically add (and then remove) some fields (0 to n) from a select.

Every item should be removed from the list after being added so it can't be selected twice.

For example I have a select like this:

 <select name="list">
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
    <option value="4">D</option>
  </select>

And I want to add a new field in my form that shows A and D and stores their values so I can get it through a POST. Then if I click on the select, there will be just B and C.

Can you help me?

  • 写回答

3条回答 默认 最新

  • dsljpwi494719 2015-07-27 13:58
    关注

    What type of fields do you want? Input type text? If so:

    $("[name=list]").on("change", function (e) {
        var val = $(this).val();
        if (val.length > 0) {
            $(this).find("option:selected").remove();
            $("<input>").attr("name", "the-name").val(val).appendTo($("#the-form"))
        }
    });
    

    check out the fiddle https://jsfiddle.net/etoysp7b/1/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?