Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 794
Nagaraj Tantri Avatar asked Sep 02 '10 12:09

Nagaraj Tantri


People also ask

What is the purpose of the name attributes?

The name attribute specifies a name for an HTML element. This name attribute can be used to reference the element in a JavaScript. For a <form> element, the name attribute is used as a reference when the data is submitted.

What is the use of name attribute in input?

The name attribute specifies the name of an <input> element. The name attribute is used to reference elements in a JavaScript, or to reference form data after a form is submitted. Note: Only form elements with a name attribute will have their values passed when submitting a form.

What is name in checkbox for in HTML?

The Input Checkbox name property in HTML DOM is used to set or return the value of name attribute of a input checkbox field. The name attribute is required for each input field. If the name attribute is not specified in an input field then the data of that field would not be sent at all.

What is the use of value attribute in checkbox?

The value attribute is one which all <input> s share; however, it serves a special purpose for inputs of type checkbox : when a form is submitted, only checkboxes which are currently checked are submitted to the server, and the reported value is the value of the value attribute.


1 Answers

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.

like image 53
JoseK Avatar answered Sep 20 '22 05:09

JoseK