How to get a value from a HTML Multiple Checkbox Element using JQuery

Posted on

In order to review on similar topic, this article is made and it is written so that it can be a perfect reminder whenever another problem comes up regarding the matter. It is on how to take the value of selected or checked HTML Checkbox element. It will not only focus on one checkbox but furthermore it is focusing on selecting multiple HTML Checkbox element selected.

For an example, if there are several checkbox available in the web page as shown in the following HTML script defined the HTML Checkbox element :

<input id="chkbox" type="checkbox" value="1" />
<input id="chkbox" type="checkbox" value="2" />
<input id="chkbox" type="checkbox" value="3" />

As it can be seen from the above snippet code there are three HTML Checkbox element where each of them can be chosen or the three of them can all be selected.  And furthermore there are a condition where those three cannot be selected either. So, how can the value from each of HTML Checkbox element  selected or it is being checked will be retrieved  ?.

In this article, there are a script or a snippet code which can be used in order to check against several HTML Checkbox element defined as shown in the script or snippet code defined above :

var checkboxes = [];
      checkboxes[$(this).val()] = $(this).val();

As shown above, there is a declaration of an array variable strarted with ‘var’ reserved keyword. It is followed by the name of the array variable which in the context of this article, it is named ‘checkboxes’. It is assigned with a default square brackets indicates an array variable. Below is the definition of the array variable  :

var checkboxes = [];

The declaration of the array variable above is not the type of an associative array or an array where the index of the array itself is represented with a string. Array in Javascript has an index where the index itself is a number. After defining the script, the detection process is very important where it is detecting the change happened in the HTML Checkbox element. If it is selected or if it has a checked event, then get the value and store it to a variable which has been defined and in the context of this article, it is called ‘checkboxes’. In order to prove that the value is actually taken from the HTML Checkbox element, just trigger an error or a message displaying the content of the variable mentioned. For detecting the HTML Checkbox element, primarily about the usage of the script snippet code, it can be viewed in the article titled ‘How to detect Element HTML Checkbox checked using JQuery’ in this link.

Leave a Reply