使用jQuery根据输入的值创建多个输入字段

时间:2012-11-29 07:37:46

标签: javascript jquery html

我有一个表格,我向用户询问他们需要多少文件输入,我想根据答案动态生成合适数量的文件浏览输入。

这是我的尝试:

$("#howmany").change(function() 
{
    var htmlString = "";
    var len = $(this).val();
        for (var i = 0; i <= len; i++) 
        {
            htmlString += "
                    <tr>
                    <td>
                    <input name="ufile[]" type="file" id="ufile[]" size="50" />
                    </td>
                    </tr>
                    ";                      
        }
        $("#dynamic_upload").html(htmlString);
}

HTML

<input id="howmany" />

<table id="dynamic_upload"> 
</table>

这个想法是根据输入的数字生成重复输入的“单位”。

但它不起作用,不知道我哪里出错了?

编辑:更明确“它不起作用”(道歉)。当我包含这段代码时,在将数字输入“howmany”字段后,没有可见的反应。没有出现错误消息,但是 - 某处有错误日志,我不知道如何阅读? (新的)

2 个答案:

答案 0 :(得分:2)

无法创建类似的字符串。尝试:

        htmlString += "<tr>";
        htmlString += "<td>";
        htmlString += '<input name="ufile[]" type="file" id="ufile[]" size="50" />';
        htmlString += "</td>";
        htmlString += "</tr>";

另外请记住,如果字符串包含双引号,则需要在字符串周围使用单引号,或者将其转义。

您在函数末尾也缺少);

    $("#dynamic_upload").html(htmlString);
} <--- this should be  });

答案 1 :(得分:1)

您不能在JavaScript字符串中添加换行符。此外,您在字符串中使用双引号(即<input>属性)。可能的重写:

htmlString += '<tr><td><input name="ufile[]" type="file" id="ufile[]" size="50"></td></tr>';

将来,请提供一个比“它不起作用”更具描述性的问题 - 例如,您是否收到任何错误消息?