我需要将一些输入文本框的内容拉入数据库。显示第一个框,但我正在使用此Javascript动态创建其中一些:
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter !== limit) {
var newdiv = document.createElement('div');
newdiv.innerHTML = " <input type='text' name='myInputs[]' size=40>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
如何为表单添加一个值,对于每个创建的框都是不同的,以便我可以在PHP中引用它们?
谢谢!
答案 0 :(得分:0)
编辑:从头开始,我从来没有尝试过使用数组来对输入进行分组,但它的工作方式却是如此。将输入的名称保留为myInputs [],但在php中引用如下:
$_POST[myInputs][0]
为您的第一个字段和
$_POST[myInputs][1]
为第二个等..
答案 1 :(得分:0)
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.js"></script>//use jQuery. it makes life easy.
<script>!window.jQuery && document.write(unescape('%3Cscript src="js/libs/jquery-1.4.2.js"%3E%3C/script%3E'))</script>
<script>
$(document).ready(function(){//fire when the page is ready
$('.addFields').click(function(){//any time someone clicks on a element with the class addFields
if( $('.myInputs').length < 10 ){ // if there are less than 10 input fields...
$($(this).attr('rel')).append("<br/><input type='text' name='myInputs[]' class='myInputs' size='40' id='myInputs"+($('.myInputs').length)+"'>");
// add another input field with an ID equal to it's place in line.
}
});
});
</script>
</head>
<body >
<a rel="#addToMe" class="addFields" href="#">Add a field</a><!-- the triggering element this can be anything that can be clicked on-->
<div id="addToMe"><!-- the element holding our input fields, new ones get added to the back of here, note that the trigger's rel attribute is the ID of this attribute and started with a "#' ID identifier-->
<input type='text' name='myInputs[]' class='myInputs' size='40' id='myInputs0'>
</div>
</body>