JQuery quiz app - use <id> tag to toggle variable on/off

Posted by hairyllama on Stack Overflow See other posts from Stack Overflow or by hairyllama
Published on 2011-03-18T15:59:57Z Indexed on 2011/03/18 16:09 UTC
Read the original article Hit count: 188

Filed under:
|
|
|
|

Hi, I am writing a jquery phonegap quiz app and have a number of categories from which a user can select via checkbox. Relevant questions belonging to those categories are then returned. However, I have two huge switch statements to change the relevant variables from 0 to 1 if the checkbox for that category is selected and vice versa (this info is used to build a compound db query).

The value of the variable behind the checkbox is only ever 0 or 1, so is there a better way to do this?

My HTML is:

<h2>Categories</h2>
      <ul class="rounded">
          <li>Cardiology<span class="toggle"><input type="checkbox" id="cardiology" /></span></li>
          <li>Respiratory<span class="toggle"><input type="checkbox" id="respiratory" /></span></li>
          <li>Gastrointestinal<span class="toggle"><input type="checkbox" id="gastrointestinal" /></span></li>
          <li>Neurology<span class="toggle"><input type="checkbox" id="neurology" /></span></li>
      </ul>

My Javascript is along the lines of:

var toggle_cardiology = 0;
var toggle_respiratory = 0;
var toggle_gastrointestinal = 0;
var toggle_neurology = 0;

$(function() {
$('input[type="checkbox"]').bind('click',function() {
    if($(this).is(':checked')) 
    {
        switch (this.id)
        {
           case "cardiology":
            toggle_cardiology = 1;
            break;
           case "respiratory":
            toggle_respiratory = 1;
            break;
           case "gastrointestinal":
            toggle_gastrointestinal = 1;
            break;
           case "neurology":
            toggle_neurology = 1;
            break;

etc. (which is cumbersome with 10+ categories plus an else statement with a switch to change them back)

I'm thinking of something along the lines of concatenating the HTML id tag onto the "toggle_" prefix - in pseudocode:

if (toggle_ + this.id == 1){
    toggle_ + this.id == 0}

if (toggle_ + this.id == 0){
    toggle_ + this.id == 1}

Thanks, Nick.

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery