Home > Software design >  how to select certain checkbox in javascript
how to select certain checkbox in javascript

Time:07-21

I want to choose the recycle checkbox but not all the checkboxes. but my code run out with all the checkboxes. how to solve it so that only my recycle checkbox can be selected all. The main code for the select all button is function checkAllRecycles().

var person = [];
person["person1"] = 1;
person["person2"] = 2;
person["person3"] = 3;
person["person4"] = 4;
person["person5"] = 5;

var elec = [];
elec["elecuse"] = 0;
elec["elec1"] = 100 * (5455 / 12);
elec["elec2"] = 150 * (5455 / 12);
elec["elec3"] = 200 * (5455 / 12);
elec["elec4"] = 250 * (5455 / 12);
elec["elec5"] = 300 * (5455 / 12);
elec["elec6"] = 350 * (5455 / 12);
elec["elec7"] = 400 * (5455 / 12);
elec["elec8"] = 450 * (5455 / 12);
elec["elec9"] = 500 * (5455 / 12);
elec["elec10"] = 550 * (5455 / 12);
elec["elec11"] = 600 * (5455 / 12);
elec["elec12"] = 650 * (5455 / 12);
elec["elec13"] = 700 * (5455 / 12);

var petrol = [];
petrol["petroluse"] = 0;
petrol["petrol1"] = 100 * 404;
petrol["petrol2"] = 200 * 404;
petrol["petrol3"] = 300 * 404;
petrol["petrol4"] = 400 * 404;
petrol["petrol5"] = 500 * 404;
petrol["petrol6"] = 600 * 404;
petrol["petrol7"] = 700 * 404;
petrol["petrol8"] = 800 * 404;
petrol["petrol9"] = 900 * 404;

function getNumberperson() {
  var numberperson = 0;
  var theForm = document.forms["energyform"];
  var selectedPerson = theForm.elements["selectedperson"];
  for (var i = 0; i < selectedPerson.length; i  ) {
    if (selectedPerson[i].checked) {
      numberperson = person[selectedPerson[i].value];
    }
  }
  return numberperson;
}

function getElectotal() {
  var electotal = 0;
  var theForm = document.forms["energyform"];
  var selectedElec = theForm.elements["electricity"];
  electotal = elec[selectedElec.value];
  return electotal;
}

function getPetroltotal() {
  var petroltotal = 0;
  var theForm = document.forms["energyform"];
  var selectedPetrol = theForm.elements["petrol"];
  petroltotal = petrol[selectedPetrol.value];
  return petroltotal;
}

function waste() {
  var mustwaste = 0;
  var theForm = document.forms["energyform"];
  var waste = theForm.elements["waste"];

  if (waste.checked == true) {
    mustwaste = (692 / 12);
  }
  return mustwaste;
}

function recyclealu() {
  var recyclealu = 0;
  var theForm = document.forms["energyform"];
  var yesalu = theForm.elements["yesalu"];

  if (yesalu.checked == true) {
    recyclealu = -89.38;
  }
  return recyclealu;
}

function recycleplas() {
  var recycleplas = 0;
  var theForm = document.forms["energyform"];
  var yesplas = theForm.elements["yesplas"];

  if (yesplas.checked == true) {
    recycleplas = -35.56;
  }
  return recycleplas;
}

function checkAllRecycles() {
  const recycleBoxes = document.querySelectorAll('input[type="checkbox"]');

  if (recycleBoxes) {
    recycleBoxes.forEach((recycleBox) => {
      if (!recycleBox.checked) {
        recycleBox.checked = 'checked';
      }
    })
  }
  calculateTotal();
}

function calculateTotal() {
  var totalco = getNumberperson() * getPetroltotal()   getNumberperson() * getElectotal()   waste()   recyclealu()   recycleplas();

  //display the result

  document.getElementById('totalConsumption').innerHTML =  totalco.toFixed(2);

}

//add a function to hide the result on page loading at the start
function hideTotal() {
  document.getElementById('totalConsumption').innerHTML = "0";
}

function vwaste() {
  var cw = document.getElementsByName('waste');
  for (var i = 0; i < cw.length; i  ) {
    if (cw[i].type == 'checkbox') {
      if (cw[i].checked) {
        return true
      }
    }
  }
  return false;
}

function allvalidate() {
  var error = document.getElementById("error")
  if (!vwaste()) {
    // Changing content and color of content
    error.textContent = "Waste must be select"
    error.style.color = "red"
    return false;
  }
  return true;


}
<body onl oad='hideTotal()'>
  <div id="all">
    <form action="/action_page.php" id="energyform" onsubmit="return false;">
      <div>
        <div >
          <fieldset>
            <legend>Carbon Footprint Calculator</legend>
            <label>Number of Person Live in Household</label><br/>
            <label class='radiolabel'><input type="radio"  name="selectedperson" value="person1" onclick="calculateTotal()" />1&nbsp</label>
            <label class='radiolabel'><input type="radio"  name="selectedperson" value="person2" onclick="calculateTotal()" />2&nbsp</label>
            <label class='radiolabel'><input type="radio"  name="selectedperson" value="person3" onclick="calculateTotal()" />3&nbsp</label>
            <label class='radiolabel'><input type="radio"  name="selectedperson" value="person4" onclick="calculateTotal()" />4&nbsp</label>
            <label class='radiolabel'><input type="radio"  name="selectedperson" value="person5" onclick="calculateTotal()" />5&nbsp</label>
            <br/>
            <label><i ></i>Waste</label>
            <input type="checkbox" id="waste" name='waste' onclick="calculateTotal()" /><span id="error"></span>

            <hr><label><i ></i>Energy Consumption Per Month</label></hr>
            <br/>
            <label>&nbspElectricity&nbsp&nbsp&nbsp&nbsp</label>
            <select id="electricity" name='electricity' onchange="calculateTotal()">
              <option value="elecuse">0kWh</option>
              <option value="elec1">100kWh</option>
              <option value="elec2">150kWh</option>
              <option value="elec3">200kWh</option>
              <option value="elec4">250kWh</option>
              <option value="elec5">300kWh</option>
              <option value="elec6">350kWh (Avg US)</option>
              <option value="elec7">400kWh (Avg MY)</option>
              <option value="elec8">450kWh</option>
              <option value="elec9">500kWh (Avg AS)</option>
              <option value="elec10">550kWh</option>
              <option value="elec11">600kWh</option>
              <option value="elec12">650kWh</option>
              <option value="elec13">700kWh</option>

            </select>
            <br/>
            <br/>
            <label>&nbspPetrol&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</label>
            <select id="petrol" name='petrol' onchange="calculateTotal()">
              <option value="petroluse">0</option>
              <option value="petrol1">100</option>
              <option value="petrol2">200</option>
              <option value="petrol3">300</option>
              <option value="petrol4">400</option>
              <option value="petrol5">500</option>
              <option value="petrol6">600</option>
              <option value="petrol7">700</option>
              <option value="petrol8">800</option>
              <option value="petrol9">900</option>
            </select>

            <hr><label><i ></i>Recycle </label></hr>
            <br/>
            <label for='yesalu' >&nbspAluminium and Steel&nbsp&nbsp</label>
            <input type="checkbox" id="yesalu" name='yesalu' onclick="calculateTotal()" />
            <br/>
            <label for='yesplas' >&nbspPlastic&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</label>
            <input type="checkbox" id="yesplas" name='yesplas' onclick="calculateTotal()" />
            <br/>
            <button type="button" onclick="checkAllRecycles()">Select All</button>
            <br/>
            <p>Total CO2 produced per year per household:</p>
            <div id="totalConsumption">0</div>
            <label>pounds</label>
            <div>US Household average is 21,820 lbs per year.</div>
          </fieldset>
        </div>
        <input type='submit' id='submit' value='Submit' onclick="allvalidate()" />
        <input type='reset' id='reset' value='Reset' onclick="hideTotal()" />
      </div>
    </form>
  </div>

</body>

CodePudding user response:

Give class names to your checkboxes.

For example, I've set class name for the checbox that selects the waste option as waste.

<input type="checkbox" id="waste" name='waste'  onclick="calculateTotal()" />

And checkboxes that have functionality for the recycling the class = "recycle" name.

 <input type="checkbox" id="yesplas"  name='yesplas' onclick="calculateTotal()" />
 <input type="checkbox" id="yesalu"  name='yesalu' onclick="calculateTotal()" />

Then, in your checkAllRecycles() function, instead of

const recycleBoxes = document.querySelectorAll('input[type="checkbox"]');

go with

const recycleBoxes = document.querySelectorAll('.recycle');

and it will work.

Below is the working snippet.

NOTE: I've removed getPetroltotal() since you forgot to add it into the code.

var person = [];
person["person1"] = 1;
person["person2"] = 2;
person["person3"] = 3;
person["person4"] = 4;
person["person5"] = 5;

var elec = [];
elec["elecuse"] = 0;
elec["elec1"] = 100 * (5455 / 12);
elec["elec2"] = 150 * (5455 / 12);
elec["elec3"] = 200 * (5455 / 12);
elec["elec4"] = 250 * (5455 / 12);
elec["elec5"] = 300 * (5455 / 12);
elec["elec6"] = 350 * (5455 / 12);
elec["elec7"] = 400 * (5455 / 12);
elec["elec8"] = 450 * (5455 / 12);
elec["elec9"] = 500 * (5455 / 12);
elec["elec10"] = 550 * (5455 / 12);
elec["elec11"] = 600 * (5455 / 12);
elec["elec12"] = 650 * (5455 / 12);
elec["elec13"] = 700 * (5455 / 12);

function getNumberperson() {
  var numberperson = 0;
  var theForm = document.forms["energyform"];
  var selectedPerson = theForm.elements["selectedperson"];
  for (var i = 0; i < selectedPerson.length; i  ) {
    if (selectedPerson[i].checked) {
      numberperson = person[selectedPerson[i].value];
    }
  }
  return numberperson;
}

function getElectotal() {
  var electotal = 0;
  var theForm = document.forms["energyform"];
  var selectedElec = theForm.elements["electricity"];
  electotal = elec[selectedElec.value];
  return electotal;
}

function waste() {
  var mustwaste = 0;
  var theForm = document.forms["energyform"];
  var waste = theForm.elements["waste"];

  if (waste.checked == true) {
    mustwaste = (692 / 12);
  }
  return mustwaste;
}

function recyclealu() {
  var recyclealu = 0;
  var theForm = document.forms["energyform"];
  var yesalu = theForm.elements["yesalu"];

  if (yesalu.checked == true) {
    recyclealu = -89.38;
  }
  return recyclealu;
}

function recycleplas() {
  var recycleplas = 0;
  var theForm = document.forms["energyform"];
  var yesplas = theForm.elements["yesplas"];

  if (yesplas.checked == true) {
    recycleplas = -35.56;
  }
  return recycleplas;
}

function checkAllRecycles() {
  const recycleBoxes = document.querySelectorAll('.recycle');

  if (recycleBoxes) {
    recycleBoxes.forEach((recycleBox) => {
      if (!recycleBox.checked) {
        recycleBox.checked = 'checked';
      }
    })
  }
  calculateTotal();
}

function calculateTotal() {
  var totalco = getNumberperson()   getNumberperson() * getElectotal()   waste()   recyclealu()   recycleplas();

  //display the result

  document.getElementById('totalConsumption').innerHTML =  totalco.toFixed(2);
}

//add a function to hide the result on page loading at the start
function hideTotal() {
  document.getElementById('totalConsumption').innerHTML = "0";
}

function vwaste() {
  var cw = document.getElementsByName('waste');
  for (var i = 0; i < cw.length; i  ) {
    if (cw[i].type == 'checkbox') {
      if (cw[i].checked) {
        return true
      }
    }
  }
  return false;
}

function allvalidate() {
  var error = document.getElementById("error")
  if (!vwaste()) {
    // Changing content and color of content
    error.textContent = "Waste must be select"
    error.style.color = "red"
    return false;
  }
  return true;
}
<div id="all">
  <form action="/action_page.php" id="energyform" onsubmit="return false;">
    <div>
      <div >
        <fieldset>
          <legend>Carbon Footprint Calculator</legend>
          <label>Number of Person Live in Household</label><br/>
          <label class='radiolabel'><input type="radio"  name="selectedperson" value="person1" onclick="calculateTotal()" />1&nbsp</label>
          <label class='radiolabel'><input type="radio"  name="selectedperson" value="person2" onclick="calculateTotal()" />2&nbsp</label>
          <label class='radiolabel'><input type="radio"  name="selectedperson" value="person3" onclick="calculateTotal()" />3&nbsp</label>
          <label class='radiolabel'><input type="radio"  name="selectedperson" value="person4" onclick="calculateTotal()" />4&nbsp</label>
          <label class='radiolabel'><input type="radio"  name="selectedperson" value="person5" onclick="calculateTotal()" />5&nbsp</label>
          <br/>
          <label><i ></i>Waste</label>
          <input type="checkbox" id="waste" name='waste'  onclick="calculateTotal()" /><span id="error"></span>

          <hr><label><i ></i>Energy Consumption Per Month</label></hr>
          <br/>
          <label>&nbspElectricity&nbsp&nbsp&nbsp&nbsp</label>
          <select id="electricity" name='electricity' onchange="calculateTotal()">
            <option value="elecuse">0kWh</option>
            <option value="elec1">100kWh</option>
            <option value="elec2">150kWh</option>
            <option value="elec3">200kWh</option>
            <option value="elec4">250kWh</option>
            <option value="elec5">300kWh</option>
            <option value="elec6">350kWh (Avg US)</option>
            <option value="elec7">400kWh (Avg MY)</option>
            <option value="elec8">450kWh</option>
            <option value="elec9">500kWh (Avg AS)</option>
            <option value="elec10">550kWh</option>
            <option value="elec11">600kWh</option>
            <option value="elec12">650kWh</option>
            <option value="elec13">700kWh</option>

          </select>
          <br/>
          <hr><label><i ></i>Recycle </label></hr>
          <br/>
          <label for='yesalu' >&nbspAluminium and Steel&nbsp&nbsp</label>
          <input type="checkbox" id="yesalu"  name='yesalu' onclick="calculateTotal()" />
          <br/>
          <label for='yesplas' >&nbspPlastic&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp</label>
          <input type="checkbox" id="yesplas"  name='yesplas' onclick="calculateTotal()" />
          <br/>
          <button type="button" onclick="checkAllRecycles()">Select All</button>
          <br/>
          <p>Total CO2 produced per year per household:</p>
          <div id="totalConsumption">0</div>
          <label>pounds</label>
          <div>US Household average is 21,820 lbs per year.</div>
        </fieldset>
      </div>
      <input type='submit' id='submit' value='Submit' onclick="allvalidate()" />
      <input type='reset' id='reset' value='Reset' onclick="hideTotal()" />
    </div>
  </form>
</div>

</body>

  • Related