Display the output based on checkbox selection using JavaScript

I am working on a feature where I need to capture checkbox inputs using JavaScript and then store them in a PHP database.

Each checkbox corresponds to a specific column in the database.

If a checkbox is checked, I want to insert its value into the database. Otherwise, I will leave the column empty.

Below is the HTML and JavaScript code snippet:


var checks = document.getElementsByClassName('justtest');
var str = '';
for(i = 0; i < 3; i++){
    if(checks[i].checked === true){
        str += checks[i].value + " ";
    }
}
alert(str);
            
        

<div class="form-group">
    <div class="col-md-3">
        <div class="checkbox">
            <label>
                <input type="checkbox" value="test1" class="justtest"> Test1
            </label>
        </div>
    </div>
</div>
<div class="form-group">
    <div class="col-md-3">
        <div class="checkbox">
            <label>
                <input type="checkbox" value="test2" class="justtest"> test2
            </label>
        </div>
    </div>
</div>
<div class="form-group">
    <div class="col-md-3">
        <div class="checkbox">
            <label>
                <input type="checkbox" value="test3" class="justtest"> test3
            </label>
        </div>
    </div>
</div>
            
        

I have attempted to implement this functionality, but unfortunately, I'm not getting the desired result.


var checks = document.getElementsByClassName('justtest');
var str = [];
for(i = 0; i < 3; i++){
    if(checks[i].checked === true){
        str[i] = checks[i].value;
    }
}
alert(str[0]);
alert(str[1]);
alert(str[2]);
            
        

Answer №1

There have been some modifications made to your code: the variable str now stores an array of results, and a button has been added that will trigger the checking function. Previously, the script would only run once without giving you the chance to select any options.


        var getValues = function () {
          var str = [];
          var checks = document.getElementsByClassName('justtest');
          
          for(var i=0; i<checks.length; i++){
            if(checks[i].checked){
              str.push( checks[i].value );
            } 
          }
  
          for( var x = 0; x < str.length; x++){
            alert (str[x]);
          }
        }
      

        <div class="form-group">
           <div class="col-md-3">
              <div class="checkbox">
                 <label>
                   <input type="checkbox" value="test1" class="justtest" > Test1
                 </label>
               </div>
              </div>
             </div>

            <div class="form-group">
              <div class="col-md-3">
                <div class="checkbox">
                  <label>
                    <input type="checkbox" value="test2" class="justtest"> test2
                  </label>
                </div>
              </div>
            </div>

            <div class="form-group">
              <div class="col-md-3">
                <div class="checkbox">
                   <label>
                     <input type="checkbox" value="test3" class="justtest"> test3
                   </label>
                </div>
                <button onclick="getValues()">Check</button>
              </div>
            </div>
        

Answer №2

If you're looking to manage checkboxes using HTML, you can achieve this by assigning them all the same input name followed by '[]'. Then, when the form is submitted, PHP will interpret it as an array. You can also access the values from JavaScript.

Let's start with the HTML implementation:

Each checkbox should have this structure:

<input type="checkbox" name="justtest[]" value="owk 1">,
<input type="checkbox" name="justtest[]" value="owk 2">

Notice the use of 'justtest[]' naming convention.

During form submission, you can iterate through the posted data in PHP using a loop like this:

foreach ($_POST["justtest"] as $key => $value) {
 echo $value;
 }

For handling this in JavaScript, you can refer to the approach suggested by Marcin C in this page. Additionally, here is another JavaScript method that you can try out (Click on the button to see it in action):

function getInput(){
  var values = [];
  var inputs = document.getElementsByName("justtest[]");
  for (var i = 0; i <inputs.length; i++) {
    var inp=inputs[i];
    if(inp.checked){
     values.push(inp.value);
      }
      //alert("justtest["+i+"].value="+inp.value); this returns all with their value , we check for only checked ones
      }
 alert (values); //alert our values here
  }
<input type="checkbox" name="justtest[]" value="owk 1">
<input type="checkbox" name="justtest[]" value="owk 2">
<input type="checkbox" name="justtest[]" value="owk 3">
<input type="checkbox" name="justtest[]" value="owk 4">

<button onclick="getInput()">Get Input<button>

Answer №3

Have you placed your script tag in the head section of your document? If it is, this code will not work because the checkboxes won't be initialized yet.

Consider moving the script to the bottom of the page right before the closing body tag.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Triggering an event when the cursor enters a specific div/span/a element and again when the cursor exits the element

Here's the scenario - Imagine a contenteditable element with text inside. I'm working on creating a tagging feature similar to Twitter's mention tagging when someone types '@'. As the user types, a popover appears with suggestion ...

Creating a default option in a Select tag with React when iterating over elements using the map method

After learning that each element in the dropdown must be given by the Option tag when using Select, I created an array of values for the dropdown: a = ['hai','hello','what'] To optimize my code, I wrote it in the following ...

Unable to reinitialize MUI DatePicker after keydown event

Encountering an unusual behavior that defies explanation has left me puzzled. You can explore the code sandbox here. I am attempting to enable resetting a readOnly field by pressing DEL or BACKSPACE, but it seems to be ineffective. Oddly enough, I can suc ...

Fetch response headers not being detected by Web Worker

Currently in my chrome extension, I'm utilizing web workers to collect response header cookies from a specific website. Interestingly, when I execute the request on the main thread, the response contains all the expected cookies. However, when the exa ...

Losing authentication token when refreshing with Nuxt asyncData and Axios

While testing a get API that retrieves an array of mail data through Postman, everything seems to be working smoothly. However, when I implement the asyncData method to fetch the array in my code, it only works once. Upon page refresh, I encounter a 401 er ...

Substitute placeholders in array with information using a loop

I have a question regarding implementing an autosort feature in JavaScript. I want my page to automatically sort data rows based on different time intervals selected by the user through checkboxes. The data updates every 3 seconds, and the autosort functio ...

Simultaneous display of icon and text on Bootstrap toggle button

Currently, I am utilizing Bootstrap 3 along with Jquery. Within my coding structure, there is a button that holds an icon within a span tag (specifically using the glyphicon provided by Bootstrap). <button id="swapArchived" class="btn btn-default btn-s ...

Error Message: TokenMismatchException detected in VerifyCsrfToken.php at line 68 - New Setup Detected

After running a Laravel project smoothly for over a year in my environment, I recently encountered a hiccup. Last week, I had to reinstall everything due to a new hard drive, and since then, Laravel has ceased to function. The other developers on my team ...

Error encountered when using prisma findUnique with where clause

Trying to set up a Singup API using ExpressJS and Prisma is proving to be a bit challenging. The issue arises when I attempt to verify if a given email already exists in my database. Upon passing the email and password, an error is thrown stating Unknown ...

I'm having an issue where whenever I click on a different page, I keep getting redirected back to the first page

Upon conducting research, I discovered that by implementing the refined code below, I was able to resolve my issue (my other html was also corrected using this solution) setTimeout(function() { datatable_FTP.ajax.reload(null, false); }, 30000); Although I ...

Utilizing jQuery and DOM to interact with form elements

Below is the form content <form method="post"> <input type="hidden" name="resulttype" value="Create"> <table> <tr> <td>Full Name</td> <td><input ...

Expanding the capabilities of the JQuery submit function

Within my web application, I find myself working with several forms, each possessing its own unique id. To streamline the process, I decided to create a custom handler for the submit event in my JavaScript file: $('#form-name').submit(function(ev ...

Tips for creating $http calls in AngularJS

Having some issues with my code, as I'm unsure of the correct placement for making an $http request to a local server. api.js var express = require('express'); var router = express.Router(); var mongoose = require('mongoose'); va ...

Guide on navigating to a specific section on a different page using scrolling

Adding a link for a "read more" button is simple. Just include the href attribute like this: <a href="about.html#post2">readmore</a> In my index.html page, I have implemented Bootstrap 3 with scroll animations for navbar sections. When clicki ...

Obtaining additional information through ajax in Yii2

I have encountered an issue where, while receiving data from an ajax call, I am also getting unnecessary data such as all the contents of my PHP files. The problem is illustrated in the image below. How can I resolve this issue? https://i.stack.imgur.com ...

where is the yarn global registry located?

After updating yarn to point to my custom registry and verifying the changes, here is what I found: $yarn config list -g yarn config v1.22.10 info yarn config { 'version-tag-prefix': 'v', 'version-git-tag': true, ' ...

Failure to Display Variable Dump

Having trouble with getting the Var Dump to display properly and all I see is a white screen. Any advice or suggestions on how to fix this? <?php require('includes/config.inc.php'); require(MYSQL); $aid = FALSE; if (isset($_GET['aid&apos ...

Guide on creating 2 select inputs with distinct elements?

Imagine you have two select inputs called 'Favorite Fruits' and 'Least Favorite Fruits'. Both of them contain a list of 5 fruits. // The following code is an example to demonstrate the issue <select name='favoriteFruits'& ...

Am I on the right track with my code?

Is the code I've written sufficient to position text above an image? It resembles the orange "Ask Question" button on StackOverflow, but without being a clickable button or link. The text is surrounded by an orange color and it works fine, but I' ...

What is the best way to retrieve the 'date,time' column from a MySQL database and use it as input for the google chart DateRangeFilter?

I am facing an issue with a column in my dataset that contains date-time values, such as '2017-2-2 10:30:20'. I need to use these rows as an input for a Date Range Filter in Google Chart. Can someone guide me on how to achieve this? I attempted ...