Sitemap / Advertise

Information



Tags



Share

How to elicit the checked input checkbox value in JavaScript

Advertisement:


read_later

Read Later

Keywords



Keywords



read_later

Read Later

Information

Tags

Share





Advertisement

Advertisement




Definition

In this tutorial, I will show you how to detect whether a checkbox is checked by the user or not in order to get the value that of the checked input checkbox. In this way, you can create more optimized user interfaces and dashboards by merely using JavaScript basic query selectors.

Code

First of all, detect whether the container form is changed or not by adding a input event listener to the container form as shown below.

If the container form is changed, then select all checked checkbox input elements by using the querySelectorAll method.

To manage that, use this CSS selector in the querySelectorAll method: input[type='checkbox']:checked

After that, you can get all values and print them in a for loop as explained below.

Do not forget to return the data empty after getting values properly when a new checkbox selected.


var container = document.getElementById("container");
var test = document.getElementById("test");
var data = "";

container.addEventListener("input", function(){
var elements = document.querySelectorAll("input[type='checkbox']:checked");
for(var i=0;i<elements.length;i++){
data += elements[i].value + " / ";
}
test.innerHTML = data;
data = "";
});

Result:

BMV
Ford
Mercedes
Audi
Fiat
Jeep

Select a checkbox...