简体   繁体   中英

What is the purpose of the `name` attribute in a checkbox input element?

I went through many online documents for the checkbox input in XHTML. Can anyone clear my doubt? What does this name field actually stand for?

Milk: <input type="checkbox" name="checkbox" value="Milk">
Chocolate: <input type="checkbox" name="checkbox" value="chocolate">
Cold Drink: <input type="checkbox" name="checkbox" value="Cold Drink">

I thought it was an identifier for that particular checkbox, which can later be used in other file by just referring their name, but given that all the checkbox had same name, why even specify it? A little confused of this.

Dont be confused because of name="checkbox" . It could more logically be name="drink" and type=checkbox .

In the above case, you have multiple checkboxes with the same name. When several checkboxes have the same name, the form will send a group of values to the server in the request. Note: only the values of the checked checkboxes will be sent to the server.

Ideally these are used to allow multiple choice questions where more than one answer is allowed. As opposed to radio buttons, where only one answer is allowed among the options.

Update:

On the receiving side, if you're using JSP for example - the values of the selected checkboxes will be available as request.getParameterValues("drink") or request.getParameterValues("checkbox") in your actual case. This is where the name attribute is used.

The name attribute is used to reference form data after it's submitted, and to reference the data using JavaScript on the client side.

Source: http://reference.sitepoint.com/html/input/name

Basically, what you've described. When the form is submitted, you can access the values of the form elements through the name you ascribe to them.

The only place where you would want to have multiple input s with the same name is when they are radio buttons, in which case it is used to indicate which one of them belongs to the same group and thus only one of which can be selected at a time.

The name attribute is used to identify a checkbox. Which you could parse into a object like so {checkboxName1: 'checkboxValue2', checkboxName2: 'checkboxValue2'}

“名称”与数据库记录相同,每个字段都应该有一个名称,所以当您点击提交时,数据将记录到数据库中~~~~~

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM