Note that there are some explanatory texts on larger screens.

plurals
  1. POJQuery quiz app - use <id> tag to toggle variable on/off
    primarykey
    data
    text
    <p>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).</p> <p>The value of the variable behind the checkbox is only ever 0 or 1, so is there a better way to do this?</p> <p>My HTML is:</p> <pre><code>&lt;h2&gt;Categories&lt;/h2&gt; &lt;ul class="rounded"&gt; &lt;li&gt;Cardiology&lt;span class="toggle"&gt;&lt;input type="checkbox" id="cardiology" /&gt;&lt;/span&gt;&lt;/li&gt; &lt;li&gt;Respiratory&lt;span class="toggle"&gt;&lt;input type="checkbox" id="respiratory" /&gt;&lt;/span&gt;&lt;/li&gt; &lt;li&gt;Gastrointestinal&lt;span class="toggle"&gt;&lt;input type="checkbox" id="gastrointestinal" /&gt;&lt;/span&gt;&lt;/li&gt; &lt;li&gt;Neurology&lt;span class="toggle"&gt;&lt;input type="checkbox" id="neurology" /&gt;&lt;/span&gt;&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>My Javascript is along the lines of:</p> <pre><code>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; </code></pre> <p>etc. (which is cumbersome with 10+ categories plus an else statement with a switch to change them back)</p> <p>I'm thinking of something along the lines of concatenating the HTML id tag onto the "toggle_" prefix - in pseudocode:</p> <pre><code>if (toggle_ + this.id == 1){ toggle_ + this.id == 0} if (toggle_ + this.id == 0){ toggle_ + this.id == 1} </code></pre> <p>Thanks, Nick.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload