Adding a value to a dynamic form
I need to pull the contents of some input text boxes into a database. The first box is displayed but I'm using this Javascript to create some of them dynamically:
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++;
}
}
How can I add a value to the form which will be different for each b开发者_StackOverflow社区ox created so I can reference them in PHP?
Thanks!
Edit: scratch that, I've never tried using an array to group inputs, but it works so use that instead. Keep the name of your inputs as myInputs[] but reference in php like this:
$_POST[myInputs][0]
for your first field and
$_POST[myInputs][1]
for the second etc..
<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>
精彩评论