Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
163 views
in Technique[技术] by (71.8m points)

php - HTML Element Array, name="something[]" or name="something"?

I saw something on this site : Handling array of HTML Form Elements in JavaScript and PHP http://www.ajaxprojects.com/ajax/tutorialdetails.php?itemid=343

It said about put the array in name property and how the get the input collection's value. e.g. name="education[]"

But as I know, HTML input element is array-ready by name. On client-side (GetElementsByName) or server-side ($_POST in PHP or Request.Form in ASP.NET) for example: name="education", so what is the different with or with not the []?

question from:https://stackoverflow.com/questions/4688880/html-element-array-name-something-or-name-something

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

PHP uses the square bracket syntax to convert form inputs into an array, so when you use name="education[]" you will get an array when you do this:

$educationValues = $_POST['education']; // Returns an array
print_r($educationValues); // Shows you all the values in the array

So for example:

<p><label>Please enter your most recent education<br>
    <input type="text" name="education[]">
</p>
<p><label>Please enter any previous education<br>
    <input type="text" name="education[]">
</p>
<p><label>Please enter any previous education<br>
    <input type="text" name="education[]">
</p>

Will give you all entered values inside of the $_POST['education'] array.

In JavaScript, it is more efficient to get the element by id...

document.getElementById("education1");

The id doesn't have to match the name:

<p><label>Please enter your most recent education<br>
   <input type="text" name="education[]" id="education1">
</p>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...