I am in the process of creating several checkboxes and am looking to incorporate some added functionality

Currently, I am working on a project that involves creating multiple checkboxes. My goal is to implement a specific functionality where only one checkbox can be checked in each group with the correct or incorrect value. Once all groups have been selected, the submit button should become enabled. When the submit button is clicked, the values of each group (right or wrong answer) should be displayed. How should I approach implementing this?

function isChecked(checkbox, sub1) {
    document.getElementById(sub1).disabled = !checkbox.checked;
}


$("input:checkbox").on('click', function() {
    var $box = $(this);
    if ($box.is(":checked")) {
        var group = "input:checkbox[name='" + $box.attr("name") + "']";
        $(group).prop("checked", false);
        $box.prop("checked", true);
        //alert("checked");

    } else {
        $box.prop("checked", false);
    }

    var bool;
    $("input.checkbox").change(function() {
        bool = $(".checkbox:not(:checked)").length != 6;

        // enable/disable
        $("#submitbutton").prop('disabled', bool).addClass('btn');

        // $("#submitbutton").removeAttr("disabled", bool).addClass("btn");
        //$('#submitbutton').removeClass('btn1').prop(':disabled', bool).addClass('btn');
        <!--alert('right')-->
    }).change('color');
    

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="checkbox" class="checkbox checkbox_1" id="button0" name="fooby[0][]" value="chk0" />
<input type="checkbox" class="checkbox checkbox_1" id="button1" name="fooby[0][]" value="chk0" />
<br>

<input type="checkbox" class="checkbox checkbox_1" id="button2" name="fooby[1][]" value="chk1" />
<input type="checkbox" class="checkbox checkbox_1" id="button3" name="fooby[1][]" value="chk2" /><br>

<input type="checkbox" class="checkbox checkbox_1" id="button4" name="fooby[2][]" value="chk3" />
<input type="checkbox" class="checkbox checkbox_1" id="button5" name="fooby[2][]" value="chk4" />
<br>

<input type="checkbox" class="checkbox checkbox_1" id="button6" name="fooby[3][]" value="chk5" />
<input type="checkbox" class="checkbox checkbox_1" id="button7" name="fooby[3][]" value="chk6" />
<br>

<input type="checkbox" class="checkbox checkbox_1" id="button8" name="fooby[4][]" value="chk7" />
<input type="checkbox" class="checkbox checkbox_1" id="button9" name="fooby[4][]" value="chk8" />
<br>

<input type="checkbox" class="checkbox checkbox_1" id="button10" name="fooby[5][]" value="chk9" />
<input type="checkbox" class="checkbox checkbox_1" id="button11" name="fooby[5][]" value="chk10" /> <br>

<input type="submit" value="Submit" id="submitbutton" disabled="disabled" class="btn" />

Answer №1

Instead of using Checkbox, you can opt for RadioButton as mentioned in the comments. This will automatically handle the checking process. However, to activate the submit button, you need to perform a calculation. You have to determine if half of the total number of radio buttons are checked:

if($("input[type='radio']").length/2==$("input[type='radio']:checked").length)
{
$(".btn").prop("disabled","");
}

Here is a demonstration:

$("input[type='radio']").on("change",function(){
if($("input[type='radio']").length/2==$("input[type='radio']:checked").length)
{
$(".btn").prop("disabled","");
}

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<input type="radio" class="checkbox checkbox_1" id="button0" name="fooby[0][]" value="chk0" />   
  <input type="radio"  class="checkbox checkbox_1" id="button1" name="fooby[0][]" value="chk0" />
     <br>

    <input type="radio" class="checkbox checkbox_1" id="button2" name="fooby[1][]" value="chk1"  /> 
    <input type="radio" class="checkbox checkbox_1"  id="button3" name="fooby[1][]" value="chk2" /><br>

  <input type="radio" class="checkbox checkbox_1" id="button4" name="fooby[2][]" value="chk3" />   
  <input type="radio"  class="checkbox checkbox_1" id="button5" name="fooby[2][]" value="chk4" />
     <br>

     <input type="radio" class="checkbox checkbox_1" id="button6" name="fooby[3][]" value="chk5" />   
  <input type="radio"  class="checkbox checkbox_1" id="button7" name="fooby[3][]" value="chk6" />
          <br>

     <input type="radio" class="checkbox checkbox_1" id="button8" name="fooby[4][]" value="chk7" />   
  <input type="radio"  class="checkbox checkbox_1" id="button9" name="fooby[4][]" value="chk8" />
               <br>

     <input type="radio" class="checkbox checkbox_1" id="button10" name="fooby[5][]" value="chk9" />   
  <input type="radio"  class="checkbox checkbox_1" id="button11" name="fooby[5][]" value="chk10" /> <br>
    
<input type="submit" value="Submit"  id="submitbutton" disabled="disabled" class="btn"/>

Answer №2

<SECTION ID=PRIMARY>

<SCRIPT>

HTML = [];
function DISPLAY(L, X) { HTML.push(L.split("#").join(X)); }
function FLUSH_CONTENT() { document.write(HTML.join("")); HTML = []; }

COOKIE = "RESPONSES";
function StoreCookie(NAME, VALUE) { var E = new Date(); E.setFullYear(E.getFullYear() + 5); document.cookie = NAME + "=" + VALUE + ";Expires=" + E.toGMTString(); }
function RetrieveCookie(NAME) { var i, e, s, K = document.cookie.split(";"); for (i = 0; i < K.length; i++) { for (s = 0; K[i].charCodeAt(s) < 33; s++); e = K[i].indexOf("="); if (K[i].substring(s, e) == NAME) return K[i].slice(++e); } return ""; }

BOX_COLOR = "003366";
TEXT_COLOR = "FFFFCC";
ROW_COLORS = "334455 667788".split(" ");
QUESTIONS = "Can you play the piano?|Do you wear glasses?|Have you ever traveled to Europe?|Is pizza your favorite food?|Are you a morning person?|Do you enjoy hiking?|Have you seen the Northern Lights?|Agree or disagree: Music is universal.|Do you like spicy food?|Did you participate in a marathon before?".split("|");

ANSWER = RetrieveCookie(COOKIE);
if (ANSWER && ANSWER != null) ANSWER = ANSWER.split(","); else ANSWER = [];
for (i = ANSWER.length; i < QUESTIONS.length; i++) ANSWER.push(0);

DISPLAY("<TABLE CELLSPACING=1 CELLPADDING=7 BGCOLOR=#>", BOX_COLOR);
DISPLAY("<TR><TD>#True<TD>#False<TD>#Questions", "<FONT COLOR=" + TEXT_COLOR + ">");
for (i = 0; i < QUESTIONS.length; i++)
{
  DISPLAY("<TR BGCOLOR=#>", ROW_COLORS[i&1]);
  DISPLAY("<TD><CENTER><INPUT "+(ANSWER[i]==1?"CHECKED":"")+" NAME=X#A TYPE=CHECKBOX onClick='SELECT(#, 1);'>", i);
  DISPLAY("<TD><CENTER><INPUT "+(ANSWER[i]==2?"CHECKED":"")+" NAME=X#B TYPE=CHECKBOX onClick='SELECT(#, 2);'>", i);
  DISPLAY("<TD onClick='SELECT(#, 0);'><FONT COLOR="+TEXT_COLOR+">"+(i+1)+". " + QUESTIONS[i], i);
}
DISPLAY("</TABLE><P>");
DISPLAY("<INPUT TYPE=BUTTON VALUE=' Get Responses ' onClick='alert(ANSWER);'>");
DISPLAY("<INPUT TYPE=BUTTON VALUE=' Clear Responses ' onClick='ClearResponses();'>");
DISPLAY("<INPUT TYPE=BUTTON "+(isComplete()?"":"DISABLED")+" NAME=NEXT VALUE=' NEXT ' onClick='Proceed();' onMouseOver='CheckResponses();'>");
FLUSH_CONTENT();

function SELECT(N, V)  // Click event handler
{
  var A = 1;
  if (ANSWER[N] == 1 || (ANSWER[N] == 0 && V == 2)) A = 0;
  ANSWER[N] = (A) ? 1 : 2;
  eval("document.MAIN.X"+N+"A.checked = A;");
  eval("document.MAIN.X"+N+"B.checked = !A;");

  CheckResponses();
  SaveResponses();
}

function isComplete() { for (var i = 0; i < QUESTIONS.length; i++) if (ANSWER[i] == 0) return 0; return 1; }

function AllowNext() { document.MAIN.NEXT.disabled = false; }

function CheckResponses() { if (isComplete()) AllowNext(); }

function Proceed() { location.href = "http://www.yahoo.com"; }

function SaveResponses() { StoreCookie(COOKIE, ANSWER.join(",")); }

function ClearResponses()
{
  for (var i = 0; i < QUESTIONS.length; i++)
  {
    ANSWER[i] = 0;
    eval("document.MAIN.X"+i+"A.checked = false;");
    eval("document.MAIN.X"+i+"B.checked = false;");
  }
  document.MAIN.NEXT.disabled = true;
  StoreCookie(COOKIE, "");
}

</SCRIPT>

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

Creating a Website for Compatibility with NoScript

During my journey of building a nameplate site from the ground up for myself, I have delved into the realms of learning and establishing my online presence. The highlight of my project is a sleek tabbed site that employs AJAX and anchor navigation to seaml ...

How to Transform JSON Element into a JavaScript Array in AngularJS?

Implementing AngularJS to fetch values in JSON format using $resource call. The model element I require is a Javascript array structured as: [ [1328983200000, 40], [1328983200000, 33], [1328983200000, 25], [1328983200000, 54], [1328983200000, 26], [1328 ...

Problem with Flickity's is-selected feature

I am currently exploring Flickity and its functionality. I have a carousel that auto-plays, with the selected cell always placed in the middle and highlighted with a grey background. However, I would like to customize it so that the selected cell is positi ...

Making changes to a JSON File

I've been attempting to integrate a jQuery gantt chart into my WordPress website as a plugin. However, I've hit a roadblock when it comes to editing the data.json file. My approach involves using a PHP form to add a new item. Upon form submission ...

Determine whether a WebElement contains a particular content within the :after pseudo class

After locating my element in Selenium, I've come across an interesting challenge. IWebElement icon = box.FindElement(By.ClassName("box-icon")); Sometimes, this element (icon) has a content set as follows: &:after { content: $icon-specia ...

Is it possible to have two router.js files within a single Angular project?

Encountering a dilemma in my Angular UI routing project with rendering the view. Contemplating using two router.js files. Is it feasible to include two router.js files in one project? What drawbacks might arise from this approach? ...

I am attempting to assign a default value to a TextField by retrieving data from a GetMapping call in React, however, the value is not being successfully set

I am facing an issue with setting a default value for a TextField in my code. Even though I am trying to populate it with data from a GetMapping call, the value is not being set as expected. Here is the JSON response I receive from the API call: { "id": 1 ...

Unable to create a responsive layout because of the use of inline CSS with "margin"

Currently, I am working on a design for a webpage that must be responsive to large, medium, and small screens. To achieve this responsiveness, I am using Material UI Grid container and placing Chips inside it with the style={{ marginLeft: 60 }} from the se ...

Is there a way to postpone these animations without relying on setTimeout?

As I develop a single-page website, my goal is to smoothly transition between sections by first animating out the current content and then animating in the new content. Currently, I have achieved this using setTimeout(), where I animate out the current con ...

What is the best way to invoke a Rest API within a Vue component?

As a newcomer to VueJS, my goal is to create a basic page featuring a pie chart displaying some data. Currently, I have successfully displayed the chart using example data. However, I now wish to populate the chart with data fetched from an API call on my ...

What is the best way to invoke an external JavaScript source using another JavaScript source?

I am trying to connect 2 different files together. file1.php and document.html file1.php has the following code in it: document.writeln('< script src="https://www.googletagservices.com/tag/js/gpt.js"> googletag.pubads().definePassback ...

What could be causing the remaining part of the template to not render when using an Angular directive?

After adding my custom directive to a template on an existing page, I noticed that only the directive was rendering and the rest of the template was not showing up as expected. Even though the controller seemed to have executed based on console logs and B ...

Ways to swap out element within ViewContainerRef in Angular

I am currently expanding my knowledge of Angular and I have encountered a challenge regarding dynamically creating components and swapping them within a single container. Here is the setup: <ng-container #container></ng-container> Here are the ...

Changes made to code within the node_modules directory do not appear in the browser

I encountered a bug in the vuejs-datepicker project on Github, prompting me to fork the repository. However, despite making changes to the forked project, these alterations are not reflected in my main project that relies on this dependency. Here's a ...

Engage in a Play app featuring AngularJS frontend navigation

Currently, I am using the Play Framework to develop a REST service and I would like the front end to be built with Angularjs in order to make rest calls. I have configured a route provider as follows: angular.module("getAbscencePlans", ["getAbscencePlans. ...

Having trouble with uploading image files in Laravel Vue.js?

I have been trying to upload my image file to a storage folder using Laravel and Vue.js. However, when I try to print the data using dd();, I get no response or error. How can I tell if I am doing it correctly? I suspect the error lies in the formData whe ...

Transform HTML content into a PDF document with page breaks

Currently, I am developing a function that involves an HTML template. The purpose of this function is to generate a dynamic template and convert it into a PDF. So far, I have been able to achieve this using the following code: var output = ''; ...

Struggling to get Django and AngularJS to play nice?

After opening the file angular.html with AngularJS in Chrome, the table displays the array of information as expected. However, when attempting to use Django with the same angular.html file, the array is not showing up in the table. Unsure of how to procee ...

Can the ::before selector be used in HTML emails?

Hey there, I have a question that might sound silly but I'm having trouble finding an answer online. My issue is with styling the bullet point before a list item in an HTML email. All I want to do is change the bullet point to a square and give it a ...

What is the reason behind utilizing the external 'this' within the inner function in Vue: $this=this?

Recently, I came across some code online that included a line $this=this. My initial interpretation was that this line assigns the 'this' of the outer function to a variable, allowing it to be used in the inner function as well. However, upon fur ...