如何在“”上动态地添加新的输入字段;keydown”;使用jQuery


how to dynamically add an new input field on "keydown" using jQuery?

每当我在表单中键入最后一个input field时,我都希望动态生成一个新的input field

这是我的HTML代码

<form method = "POST" action="test2.php" >
<input type="text" name='text1'>

因此当i个input文本在上面的input field中时,应该动态地生成新的input field

例如。

<input type="text" name='text2'>

如果我在新生成的input field中再次生成input文本,那么也应该在它之后生成新的field,我希望这些输入之间有</br>间隙。

</br><input type="text" name='text3'>

inputs下面,应该有一个submit button。当我点击这个button时,整个form(包括所有动态生成的input fields)应该使用AjaxPHP发送到数据库。

<input type="submit" value="submit">
</form>

不确定,但您可能喜欢这样的东西:

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
 $txt=new Array();
 $(function(){
     $('#go').on('click',function(){
         console.log($('form').serialize());
         })
     $('body').on('keydown','.last',function(){
         $('.last').removeClass('last');
         $('#go','body').before('</br><input class="last" type="text" name="text'+(Number($(this).attr('name').match(/[0-9]+/g))+1)+'" value="'+(Number($(this).attr('name').match(/[0-9]+/g))+1)+'"></br>');
         })
     })
</script>
</head>
<body>
<form>
<input  class="last"  type="text" name='text1' value="no text">
<input id="go" name="" type="button" />
</form>
</body>
</html>

编辑:我为您添加了一个<form>,以及一些代码,以查看单击按钮时我们发送的数据。查看结果是您的浏览器console。即:firebug或其他快捷键通常为:(F12)

在此处进行测试:http://jsfiddle.net/3jLbm9sp/1/