Accessing checkbox value in JS function

Hi,

I am trying to get the value of a checkbox into a JS function. I have been successfully able to do this for a text box but ot the checkbox.

Here is the part of the html file,

      <div>
        Names: <input id="students" type="text" value="Hans" placeholder="Fred Sarah John Ana "> (optional)<br>
        (Place comma or space between names)
        <br><br>
        <table>
          <tr>
              <td align="right">Easy:</td><td><input type="checkbox" id="easy" checked></td>
              <td align="right">Number of questions:</td><td><input type="number" id="numEasy" placeholder="10" value="10"></td>
          </tr>
        </table>
      </div>
      <div>
        <br><button onclick="simplepdf();">Generate pdf</button> of quadratic expressions.
      </div>

Here is part of the script file,

function simplepdf(){//////////////////////////////////................

  function getStudents() { // get the student string from the text input and changes it to an array students[]
    var val = document.getElementById("students").value;
    var index = val.indexOf(",");//check if there is a comma in string
    console.log("index " + index);
    if(index == -1){//no comma in string so split on a space
        students = val.split(" "); // splits the string into elements in an array
    }else{
        students = val.split(","); // splits the string into elements in an array
      }
  }
  function getSettings() {
    var easyCheck = document.getElementById("easy").value;
      console.log("easy checkbox value " + easyCheck);
    var easyNum = document.getElementById("numEasy").value;
      console.log("number of easy " + easyNum);
  }
  getSettings();
  getStudents();
............

Perhaps .value does not work for checkboxes. I can’t see what I am doing wrong here.

Thanks,

Hi @ofeyofey,

The problem is that your checkbox element doesn’t have a value attribute.[quote=“ofeyofey, post:1, topic:209800”]
<input type=“checkbox” id=“easy” checked>
[/quote]

.checked is what you can always use with checkboxes (even when it doesn’t have a value) - the value will either true if it is checked or false if it isn’t.

You would probably need to give the checkbox a value and a name if you want to pass it to the server but if it is only intended to work with JavaScript then you don’t need either of those attributes.

Note that if you do give the checkbox a value then it will have that value whether it is checked or not.

1 Like

Hi,

yes I’ve been playing with this all day. Very inefficent use of time! But anyway I have discovered exactly what you said felgall that I do need to use .checked and therefore i do not need a value for the checkbox.

My main problem was that i couldn’t see the anything in the console using firefox. Whatever way I have setup my browser to download pdf’s, a new tab opens for each new pdf and nothing outputs to the console. I switched to Chrome and at least I can see in the console what is happening now.

The following is working well,

HTML file

  <div>
    Names: <input id="students" type="text" value="Hans" placeholder="Fred Sarah John Ana"> (optional)<br>
    (Place comma or space between names)
    <br><br>
    <table>
      <tr>
  <td align="right">Easy:</td><td><input type="checkbox" id="easy"></td>
  <td align="right">Number of questions:</td><td><input type="number" id="numEasy" placeholder="10" value="10"></td>
      </tr>
      <tr>
  <td align="right">Moderate:</td><td><input type="checkbox" id="moderate"></td>
  <td align="right">Number of questions:</td><td><input type="number" id="numModerate" placeholder="10" value="10"></td>
      <tr>
  <td align="right">Hard:</td><td><input type="checkbox" id="hard"></td>
  <td align="right">Number of questions:</td><td><input type="number" id="numHard" placeholder="10" value="10"></td>
      </tr>
    </table>
  </div>

The script file

    function simplepdf(){//////////////////////////////////................
    // console.log("beginning of simplepdf function");
      function getStudents(){ // get the student string from the text input and changes it to an array students[]
var val = document.getElementById("students").value;
var index = val.indexOf(",");//check if there is a comma in string
  // console.log("index " + index);
if(index == -1){//no comma in string so split on a space
    students = val.split(" "); // splits the string into elements in an array
}else{
    students = val.split(","); // splits the string into elements in an array
  }
      }
      function getSettings(){
var easyCheck = document.getElementById("easy").checked;
  // console.log("Easy checkbox value: " + easyCheck);
var easyNum = document.getElementById("numEasy").value;
  // console.log("Number of easy: " + easyNum);
var moderateCheck = document.getElementById("moderate").checked;
  // console.log("Moderate checkbox value: " + moderateCheck);
var moderateNum = document.getElementById("numModerate").value;
  // console.log("Number of moderate: " + moderateNum);
var hardCheck = document.getElementById("hard").checked;
  // console.log("Hard checkbox value: " + hardCheck);
var hardNum = document.getElementById("numHard").value;
  // console.log("Number of hard: " + hardNum);
      }
      getStudents();
      getSettings();

Thanks for helping with this.

A checkbox is not the best option for this application. You need to have a single selection, rather than a multiple of selections. The following script makes use of radio buttons. You also need to allow people to input the student names before they are displayed. Putting your getStudents() call at the bottom of the script so that it runs on page load does not allow any entry. You need some sort of submit button that is clicked when all the input is in place.

I have also combined your getStudents() and getSettings() scripts to keep it simple.

function getInfo()
   { var i, val = document.getElementById("students").value;
     var index = val.indexOf(",");                          
     var students;
     if(index == -1)
       { students = val.split(" ");    }                        
     else{ students = val.split(","); } 
   //                        
     var myRadioObj=document.myForm.myRadio;
     for(i=0;i<myRadioObj.length;i++)
       { if(myRadioObj[i].checked)
           { var difficulty=myRadioObj[i].value;
             var questions=document.myForm["num"+difficulty].value;
             var dataString="Students= "+students+"\nDifficulty= "+difficulty+"\nQuestions= "+questions+"";
             alert(dataString); 
             return;
           }            
       }
      alert("Please select a level of difficulty");   
    }

I have placed a working program on jsFiddle :grinning:

Hi,
Thanks it is interesting how you combined the two functions getSettings() and getStudents(). But I do need radio buttons because I would like to output a combination of levels. Here is my full code,

HTML

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>pdf generater</title>
    <script src="jspdf.js"></script>
    <script src="libs/FileSaver.js/FileSaver.min.js"></script>
    <script src="jsScriptQuads.js"></script>
  </head>
  <body>
    <!-- <h1>Generate quadratic expressions</h1> -->
      <div>
        Names: <input id="students" type="text" placeholder="Fred Sarah John Anna"> (optional)<br>
        (Place comma or space between names)
        <br><br>
        <table>
          <tr id="easyRow">
              <td align="right">Easy:</td><td><input onclick="addEz();" type="checkbox" id="easy"></td>
          </tr>
          <tr id="modRow">
              <td align="right">Moderate:</td><td><input onclick="addMod();" type="checkbox" id="moderate"></td>
          </tr>
          <tr id="hardRow">
              <td align="right">Hard:</td><td><input onclick="addHard();" type="checkbox" id="hard"></td>
          </tr>
        </table>
      </div>
      <div>
        <br><button onclick="simplepdf();">Generate pdf</button> of quadratic expressions.
      </div>
  </body>
</html>

The script

//generating quadratic equations
//console.log("quadratic");
arr = [];
var range;
var fact = function(range){
  var arr = [];
  //generates a random integer in the range 1 to 'range'
  var a = Math.floor(Math.random()*(range)+1);
  //console.log("a = " + a);
  var j = 1;
  //generates a rand number in the range 1 to a
  // var num = Math.floor(Math.random()*(a)+1);
  for(var i=1; i<=a; i++){
    if(a%i===0){
      arr[j] = i;
      // console.log("arr[" + j + "]=" + arr[j]);
      j++;
    }
  }
  //console.log("arr.length=" + arr.length);
  for(var i=1; i<arr.length; i++){
    //console.log(arr[i]);
  }
  pair = [];
  var index = Math.floor(Math.random()*(arr.length-1)+1);
  //console.log("arr.length = " + arr.length);
  pair[0] = arr[index];
  //console.log("pair[" + 0 + "] = " + pair[0]);
  pair[1] = a/arr[index];
  //console.log("pair[" + 1 + "] = " + pair[1]);
  return pair;
}//end of fact() function

var quads = function(aRange,bRange){

var bool = function(){
  plusminus = Math.floor(Math.random()*2);
  if(plusminus == 0){
    plusminus = -1;
  }
  // console.log("plusminus=" + plusminus);
  return plusminus;
}//end of bool function

aFactor = fact(aRange);
a1 = bool()*aFactor[0];
a2 = bool()*aFactor[1];
cFactor = fact(bRange);
c1 = bool()*cFactor[0];
c2 = bool()*cFactor[1];
  //console.log("a1=" + a1 + ", a2=" + a2 + ", c1=" + c1 + ", c2=" + c2);
num1 = a1*a2;
if(num1 == 1){
  num1 = "";
}else if(num1 == -1){
  num1 = "-";
}
num3 = c1*c2;
if(num3 > 0){
  num3 = "+" + num3;
}else if(num3 <  0){
  num3 = "" + num3;
}
num2 = a1*c2 + a2*c1;
if(num2 > 0 || num2 ==0){
  num2 = "+" + num2;
}else if(num2 < 0){
  num2 = "" + num2;
}
if(a1 == 1){
  a1 = "";
}
if(a1 == -1){
  a1 = "-";
}
if(c1 > 0){
  c1 = "+" + c1;
}

if(a2 == 1){
  a2 = "";
}
if(a2 == -1){
  a2 = "-";
}
if(c2 > 0){
  c2   = "+" + c2;
}

//console.log("a1=" + a1);
problem = num1 + "x^2" + num2  + "x" + num3;
solution = "(" + a1 + "x" + c1 + ")(" + a2 + "x" + c2 + ")";
//console.log("problem: " + problem + ", solution: " + solution);
return [problem, solution];
}//end of quads function

function addEz(){
var row = document.getElementById("easyRow");
var cell = document.createElement("td");
var text = document.createTextNode("Number of questions: ");
cell.appendChild(text);
row.appendChild(cell);
var cell = document.createElement("td");
var detail = document.createElement("input");
detail.setAttribute("id", "numEasy");
detail.value = "10";
detail.type = "number";
cell.appendChild(detail);
row.appendChild(cell);
}

function addMod(){
var row = document.getElementById("modRow");
var cell = document.createElement("td");
var text = document.createTextNode("Number of questions: ");
cell.appendChild(text);
row.appendChild(cell);
var cell = document.createElement("td");
var detail = document.createElement("input");
detail.setAttribute("id", "numModerate");
detail.value = "10";
detail.type = "number";
cell.appendChild(detail);
row.appendChild(cell);
}

function addHard(){
var row = document.getElementById("hardRow");
var cell = document.createElement("td");
var text = document.createTextNode("Number of questions: ");
cell.appendChild(text);
row.appendChild(cell);
var cell = document.createElement("td");
var detail = document.createElement("input");
detail.setAttribute("id", "numHard");
detail.value = "10";
detail.type = "number";
cell.appendChild(detail);
row.appendChild(cell);
}

function simplepdf(){//////////////////////////////////................
// console.log("beginning of simplepdf function");
  function getStudents(){ // get the student string from the text input and changes it to an array students[]
    var val = document.getElementById("students").value;
    //issue still exists if more than one consecutive space is used
    var index = val.indexOf(",");//check if there is a comma in string
      //console.log("index " + index);
    if(index == -1){//no comma in string so split on a space
        students = val.split(" "); // splits the string into elements in an array
    }else{
        students = val.split(","); // splits the string into elements in an array
      }
  }
  function getSettings(){
    easyCheck = document.getElementById("easy").checked;
      // console.log("Easy checkbox value: " + easyCheck);
      if(easyCheck){
        easyNum = document.getElementById("numEasy").value;
      // console.log("Number of easy: " + easyNum);
      }
    moderateCheck = document.getElementById("moderate").checked;
      // console.log("Moderate checkbox value: " + moderateCheck);
      if(moderateCheck){
        moderateNum = document.getElementById("numModerate").value;
      // console.log("Number of moderate: " + moderateNum);
      }
    hardCheck = document.getElementById("hard").checked;
      // console.log("Hard checkbox value: " + hardCheck);
      if(easyCheck){
      hardNum = document.getElementById("numHard").value;
        // console.log("Number of hard: " + hardNum);
      }
      if(!easyCheck && !moderateCheck && !hardCheck){
        alert("Please choose a level of difficulty");
        exit();
      }
  }
  getStudents();
  getSettings();

  for(var k=0; k < students.length; k++){

    probs = [];
    sols = [];
    easyNum = parseInt(easyNum);
    moderateNum = parseInt(moderateNum);
    hardNum = parseInt(hardNum);
    total = easyNum + moderateNum + hardNum;
      for(var i=0; i < total; i++){
        if(i < easyNum){//number of easy questions easyNum
          aRange = 5;
          bRange = 5;
        }else if((i > (easyNum - 1)) && (i < (easyNum + moderateNum))){//number of moderate questions moderateNum
          aRange = 12;
          bRange = 12;
        }else{//number of difficult questions hardNum
          aRange = 24;
          bRange = 24;
        }

      //call quads() which returns an array with two elements one for prob and one for solution
      retArray = quads(aRange,bRange);
      var probLength = probs.push(retArray[0]);
      var solLength = sols.push(retArray[1]);
    }//end of for loop

          var line = 10;
          page = 0;
          var doc = new jsPDF();
          if(line==10){
          doc.text(20,line,students[k].toUpperCase() + " " + 'line: ' + line + ',  Task: factorise the following expressions');
          line+=10;
        }
          if(easyCheck){
            doc.text(20,line,'Easy, line: ' + line);
            line+=10;
            for(var i = 0; i < easyNum; i++){
                // doc.text(20,line,'line: ' + line + ', i: ' + i);
                doc.text(30,line, (i+1) + ". " + probs[i]);
                line+=10;
                if(line==270){
                  doc.text(20,line,'page ' + (page+1));
                  doc.addPage();
                  line=10;
                  doc.text(20,line,students[k].toUpperCase() + " " + 'line: ' + line + ',  Task: factorise the following expressions');
                  line+=10;
                }
            }
          }
          if(moderateCheck){
            doc.text(20,line,'Moderate, line: ' + line);
            line+=10;
            if(!easyCheck){
              easyNum = 0;
            }
            for(var i = easyNum; i < moderateNum + easyNum; i++){
                // doc.text(20,line,'line: ' + line + ', i: ' + i);
                doc.text(30,line, (i+1) + ". " + probs[i]);
                line+=10;
                if(line==270){
                  doc.text(20,line,'page ' + (page+1));
                  doc.addPage();
                  line=10;
                  doc.text(20,line,students[k].toUpperCase() + " " + 'line: ' + line + ',  Task: factorise the following expressions');
                  line+=10;
                }
            }
          }
          if(hardCheck){
            doc.text(20,line,'Hard, line: ' + line);
            line+=10;
            if(!moderateCheck){
              moderateNum = 0;
            }
            for(var i = moderateNum; i < hardNum + moderateNum; i++){
                // doc.text(20,line,'line: ' + line + ', i: ' + i);
                doc.text(30,line, (i+1) + ". " + probs[i]);
                line+=10;
                if(line==270){
                  doc.text(20,line,'page ' + (page+1));
                  page++;
                  doc.addPage();
                  line=10;
                  doc.text(20,line,students[k].toUpperCase() + " " + 'line: ' + line + ',  Task: factorise the following expressions');
                  line+=10;
                }
            }
          }
          doc.save(students[k] + 'ProblemSheet.pdf');

          var doc = new jsPDF();
          doc.text(20,10,students[k].toUpperCase() + ',  Solution sheet: quadratic expressions');
          for(var i=0; i < total; i++){
          doc.text(20,2*10+(i*10),(i+1) + ". " + probs[i] + " = " + sols[i]);
          }
          doc.text(20,270,"NO GRADE WILL BE GIVEN IF YOU ANSWER THE WRONG PROBLEMS");
          doc.save(students[k] + 'SolutionSheet.pdf');
       }//end of the students[] for loop
  }

This does use the jsPDF library to generate the pdf’s.
I haven’t fixed the solution sheets so that they create new pages within the file. That’s one of the many things on my todo list here.

Another issue is that if more that one space is placed between names the second space is considered an a name and so a whole new set of files is created for it.

Thanks,

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.