I would like to be able to dynamically add rows to a form (I have now included the form below) using a drop down menu. I presume this would be a javascript function, but I'm not sure.
My idea is that all that would show on the page initially is a drop down menu which defaults to '1', and one row of the form with a few fields, such as name, email, age, etc. The user is asked to select a number from the drop down menu, and then whatever number is selected, rows will be added to the form to match this number.
As an (important) aside, once the form has been completed I want to be able to submit the information in the form via email using PHP, and I wonder whether each input field would need to have a unique ID to pass to the PHP page that generates the email. I mention this in case it needs to be taken into consideration in the method that is used to add rows to the table.
I'd be grateful for any help in getting going with this.
Thanks,
Nick
Form:
<form id="myForm" method="POST">
<label>Please select the number of people you are booking for:</label>
<select id="myDropDown">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5"&开发者_运维问答gt;5</option>
</select><br/><br />
<label>name:</label> <input type="text" name="name" id="name">
<label>email:</label> <input type="text" name="email" id="email">
</form>
I would like to be able to dynamically add rows to a form using a drop down menu. I presume this would be a javascript function, but I'm not sure.
Yes, it would be easiest to do it in JavaScript. Pick a good toolkit like jQuery for helping you navigate and modify the DOM. Here's a simple skeleton:
$(function() {
var myForm = $("#myForm");
$("#myDropDown").select(function() {
var selected = $("option:selected", this).val();
$("<input/>")
.attr("type", "text")
.attr("name", selected)
.attr("id", selected)
.appendTo( myForm );
});
});
I think forms need unique names for post not id.
loop over the number selected, foreach one do this.
var newInput = document.createElement("input");
newInput.Name = "Unique name to form"
newInput.Type = "text" // or whatever
document.getElementById("formId").appendChild(newInput);
note that it could be done easier with jQuery possibly but this will work with the built in js function.
精彩评论