how to fix javascript - javascript

when the checkbox is checked by the user, I want to push the value(the numerical value are in the JS) for the checked box in an array, get the sum and display the total calories in the alert message.
here's my code so far:
var rice = 204;
var bread = 140;
var chicken = 147;
var beef = 282;
var carrots = 150;
var beans = 70;
function myFunction() {
var rice = document.getElementById("rice");
var bread = document.getElementById("bread");
var chicken = document.getElementById("chicken");
var beef = document.getElementById("beef");
var carrots = document.getElementById("carrots");
var beans = document.getElementById("beans");
const food = [];
if (rice.checked == true) {
food.push(window.rice);
} else if (bread.checked == true) {
food.push(window.bread);
} else if (chicken.checked == true) {
food.push(window.chicken);
} else if (beef.checked == true) {
food.push(window.beef);
} else if (carrots.checked == true) {
food.push(window.carrots);
} else if (beans.checked == true) {
food.push(window.beans);
}
let sum = food.reduce(function(a, b) {
return a + b;
}, 0);
console.log(sum); /*sum of array not working */
console.log(food);
}
myFunction();
<form>
<h2>Meal Plan</h2>
<h3>Dietary restrictions:</h3>
<input type="radio" name="diet" id="none" value="none" required>
<label for="none">None</label>
<br/><input type="radio" name="diet" id="vegetarian" value="vegetarian" required>
<label for="vegetarian">Vegetarian</label>
<br/><input type="radio" name="diet" id="lowcarb" value="lowcarb" required>
<label for="lowcarb">Low Carb</label>
<br />
<h3>Food items:</h3>
<input type="checkbox" name="Rice" id="rice" value="rice">
<label for="rice">Rice</label>
<br /><input type="checkbox" name="Beef" id="beef" value="beef">
<label for="beef">Beef</label>
<br /><input type="checkbox" name="Bread" id="bread" value="bread">
<label for="bread">Bread</label>
<br /><input type="checkbox" name="Beans" id="beans" value="beans">
<label for="beans">Beans</label>
<br /><input type="checkbox" name="Chicken" id="chicken" value="chicken">
<label for="chicken">Chicken</label>
<br /><input type="checkbox" name="Carrots" id="carrots" value="carrots">
<label for="carrots">Carrots</label>
<br /><br /><input type="submit" onclick="myFunction()" />
</form>
<script src="try.js"></script>
the values is not appending in the array when i check multuple boxes. it only appends the first box that i checked and doesn't include the next boxes. i cant get the sum, how can i fix that?

You can do this way
document.querySelector('form').addEventListener('click', e => {
if (e.target.matches('input[type="radio"]')) {
const checked = document.querySelector('#vegetarian').checked;
document.querySelectorAll('.meat').forEach(chk => {
chk.disabled = checked;
chk.checked = false;
});
}
});
const calories = {
rice: 204,
bread: 140,
chicken: 147,
beef: 282,
carrots: 150,
beans: 70
};
function myFunction() {
const food = [];
const veg = [];
let sum = 0;
document.querySelectorAll('input[type="checkbox"]').forEach(chk => {
if (chk.checked) {
food.push(chk.value);
if (chk.classList.contains('veg')) {
veg.push(chk.value);
}
sum += (calories[chk.value] || 0);
}
});
console.log(sum); /*sum of array not working */
alert(food);
if (veg.length < 2) {
alert('two vegs are recommendeded');
}
}
<!DOCTYPE html>
<html>
<head>
<title>Meal Plan</title>
</head>
<body>
<form onsubmit="return false;">
<h2>Meal Plan</h2>
<h3>Dietary restrictions:</h3>
<input type="radio" name="diet" id="none" value="none" required>
<label for="none">None</label>
<br/><input type="radio" name="diet" id="vegetarian" value="vegetarian" required>
<label for="vegetarian">Vegetarian</label>
<br/><input type="radio" name="diet" id="lowcarb" value="lowcarb" required>
<label for="lowcarb">Low Carb</label>
<br />
<h3>Food items:</h3>
<input type="checkbox" name="Rice" id="rice" value="rice">
<label for="rice">Rice</label>
<br /><input type="checkbox" name="Beef" class="meat" id="beef" value="beef">
<label for="beef">Beef</label>
<br /><input type="checkbox" name="Bread" id="bread" value="bread">
<label for="bread">Bread</label>
<br /><input type="checkbox" name="Beans" class="veg" id="beans" value="beans">
<label for="beans">Beans</label>
<br /><input type="checkbox" name="Chicken" class="meat" id="chicken" value="chicken">
<label for="chicken">Chicken</label>
<br /><input type="checkbox" name="Carrots" class="veg" id="carrots" value="carrots">
<label for="carrots">Carrots</label>
<br /><br /><input type="submit" onclick="myFunction()" />
</form>
</body>
</html>
Your existing if ... else if ... block got problem, it won't run the rest of else if once a condition is true.

do that this way ... (less code and more readability)
const
myForm = document.forms['my-form']
, calories =
{ rice : 204
, bread : 140
, chicken : 147
, beef : 282
, carrots : 150
, beans : 70
}
, NotVegetarianFood = ['beef', 'chicken' ]
;
myForm.oninput = e =>
{
if ( e.target.name === 'diet' )
{
let isVegetarian = (myForm.diet.value === 'vegetarian')
NotVegetarianFood.forEach( food =>
{
myForm[food].disabled = isVegetarian
if (isVegetarian)
myForm[food].checked = false
})
}
}
myForm.onsubmit = e =>
{
e.preventDefault()
let
sum = 0
, vegetables = 0
, formValues =
Array
.from(new FormData(myForm).entries() )
.reduce((res,[food,_])=>
{
if (!!calories[food])
{
vegetables += NotVegetarianFood.includes(food) ? 0 : 1
sum += calories[food]
res.push (food)
}
return res
},[])
myForm.message.textContent = (vegetables > 2)
? ''
: '2 vegetables options are recommended for a healthy meal regardless of the dietary restrictions.'
console.clear()
console.log( JSON.stringify( formValues), '\n-- calories sum =', sum )
}
fieldset {
width : 16em;
margin-bottom : .7em;
}
legend {
font-weight : bold;
}
label {
display : block;
margin-top : .4em;
}
<form name="my-form">
<h3>Meal Plan</h3>
<fieldset>
<legend>Dietary restrictions:</legend>
<label> <input type="radio" name="diet" value="none" checked > None </label>
<label> <input type="radio" name="diet" value="vegetarian" > vegetarian </label>
<label> <input type="radio" name="diet" value="lowcarb" > Low Carb </label>
</fieldset>
<fieldset>
<legend>Food items:</legend>
<label> <input type="checkbox" name="rice" > Rice </label>
<label> <input type="checkbox" name="beef" > Beef </label>
<label> <input type="checkbox" name="bread" > Bread </label>
<label> <input type="checkbox" name="beans" > Beans </label>
<label> <input type="checkbox" name="chicken" > Chicken </label>
<label> <input type="checkbox" name="carrots" > Carrots </label>
</fieldset>
<button type="submit">submit</button>
<output name="message"></output>
</form>

Related

I have these 2 tonnage calculators. The first one is working great. How can I fix the second one? Is something wrong with my Javascript?

I would also like if I could have the value printed on the screen instead of showing up as an alert. For some reason my code was working when I only had the 1 calculator on the screen but when I tried adding a second one and modifying the javascript a little bit so the second one works as well both stopped working.
THANKS!
sum = {
"al": 12,
"mm": 20,
"hm": 30,
}
let val;
window.addEventListener("load", function() { // when page loads
document.getElementById("tensile").addEventListener("click", function(e) {
var tgt = e.target; // what was clicked
if (tgt.name == "size") { // is it one of the radios?
val = tgt.value; // save the value once (DRY principle)
}
})
$('.ck').click(function() {
var a = parseFloat($('.n1').val());
var b = parseFloat($('.n2').val());
var z = 3.14;
var c = a * b * z * sum[val];
alert(c);
})
})
sum = {
"al1": 12,
"mm1": 20,
"hm1": 30,
}
let val1;
window.addEventListener("load", function() { // when page loads
document.getElementById("tensile1").addEventListener("click", function(g) {
var tgt1 = g.target; // what was clicked
if (tgt1.name == "size") { // is it one of the radios?
val1 = tgt1.value; // save the value once (DRY principle)
}
})
$('.ck1').click(function() {
var a1 = parseFloat($('.n3').val());
var b1 = parseFloat($('.n4').val());
var c1 = parseFloat($('.m2').val());
var z1 = 3.14;
var d1 = a1 * b1 * z1 * sum[val1];
alert(d1);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<h1>ROUND HOLE</h1>
Diameter<input type="text" class="n1" /><br /> Metal Thickness<input type="text" class="n2" /><br />
<h3> Select Metal </h3>
<form id="tensile">
<input type="radio" name="size" value="al">Alum
<br>
<input type="radio" name="size" value="mm">Mild Metal<br>
<input type="radio" name="size" value="hm"> Heavy Metal<br>
<br>
</form>
<hr />
<input type="button" value="Add" class="ck" />
</div>
<div>
<h1>RECTANGLE HOLE</h1>
Length<input type="text" class="n3" /><br />
width<input type="text" class="n4" /><br />
Metal Thickness<input type="text" class="m2" /><br />
<h3> Select Metal </h3>
<form id="tensile1">
<input type="radio" name="size" value="al1">Alum
<br>
<input type="radio" name="size" value="mm1">Mild Metal<br>
<input type="radio" name="size" value="hm1"> Heavy Metal<br>
<br>
</form>
<hr />
<input type="button" value="Add" class="ck1" />
</div>
Your sum object is declared twice. The second declaration overwrites the first, so the keys needed for the first calculator are lost.
The first one throw an error because you reassigned sum. For instance the first one looks for the value of al key but there isn't anymore because you reassigned it, there is al1. So you should assign sum once and it should be as following:
let sum = {
"al": 12,
"mm": 20,
"hm": 30,
"al1": 12,
"mm1": 20,
"hm1": 30,
}
Here is the working example:
let sum = {
"al": 12,
"mm": 20,
"hm": 30,
"al1": 12,
"mm1": 20,
"hm1": 30
}
let val;
window.addEventListener("load", function() { // when page loads
document.getElementById("tensile").addEventListener("click", function(e) {
var tgt = e.target; // what was clicked
if (tgt.name == "size") { // is it one of the radios?
val = tgt.value; // save the value once (DRY principle)
}
})
$('.ck').click(function() {
var a = parseFloat($('.n1').val());
var b = parseFloat($('.n2').val());
var z = 3.14;
var c = a * b * z * sum[val];
alert(c);
})
})
let val1;
window.addEventListener("load", function() { // when page loads
document.getElementById("tensile1").addEventListener("click", function(g) {
var tgt1 = g.target; // what was clicked
if (tgt1.name == "size") { // is it one of the radios?
val1 = tgt1.value; // save the value once (DRY principle)
}
})
$('.ck1').click(function() {
var a1 = parseFloat($('.n3').val());
var b1 = parseFloat($('.n4').val());
var c1 = parseFloat($('.m2').val());
var z1 = 3.14;
var d1 = a1 * b1 * c1 * z1 * sum[val1];
alert(d1);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<h1>ROUND HOLE</h1>
Diameter<input type="text" class="n1" /><br /> Metal Thickness<input type="text" class="n2" /><br />
<h3> Select Metal </h3>
<form id="tensile">
<input type="radio" name="size" value="al">Alum
<br>
<input type="radio" name="size" value="mm">Mild Metal<br>
<input type="radio" name="size" value="hm"> Heavy Metal<br>
<br>
</form>
<hr />
<input type="button" value="Add" class="ck" />
</div>
<div>
<h1>RECTANGLE HOLE</h1>
Length<input type="text" class="n3" /><br />
width<input type="text" class="n4" /><br />
Metal Thickness<input type="text" class="m2" /><br />
<h3> Select Metal </h3>
<form id="tensile1">
<input type="radio" name="size" value="al1">Alum
<br>
<input type="radio" name="size" value="mm1">Mild Metal<br>
<input type="radio" name="size" value="hm1"> Heavy Metal<br>
<br>
</form>
<hr />
<input type="button" value="Add" class="ck1" />
</div>
the corect way to code that (IMHO) :
const
myForm = document.forms['my-form']
, sDigits = new Intl.NumberFormat('en-US', { maximumFractionDigits: 4, minimumFractionDigits: 2 })
, Metal = { al: 12, mm: 20, hm: 30 }
;
myForm['bt-control-round'].onclick = () =>
{
let val = myForm['diameter-round'].valueAsNumber
* myForm['thickness-round'].valueAsNumber
* 3.14
* Metal[ myForm['metal-round'].value ]
;
// alert( `round hole:\n ${val.toFixed(4)}` )
myForm['out-control-round'].value = isNaN(val) ? 'bad entrie(s)' : sDigits.format(val)
}
myForm['bt-control-rect'].onclick = () =>
{
let val = myForm['length-rect'].valueAsNumber
* myForm['width-rect'].valueAsNumber
* myForm['thickness-rect'].valueAsNumber
// * 3.14
* Metal[ myForm['metal-rect'].value ]
;
// alert( `rectangle hole:\n ${val.toFixed(4)}` )
myForm['out-control-rect'].value = isNaN(val) ? 'bad entrie(s)' : sDigits.format(val)
}
myForm.onsubmit = evt => { evt.preventDefault() } // disable submit
form {
font-family : 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
font-size : 14px;
}
form legend {
text-transform : capitalize;
padding : 0 1em;
}
form fieldset {
margin-top : 1em;
width : 20em;
}
form .backLine,
form .backLinePlus,
form .backLinePlus * {
display : block;
float : left;
clear : both;
}
form label.cVal {
margin-top : .7em;
}
form label.cVal span {
font-size : .9em;
padding-right : .2em;
font-weight : bold;
}
form h5 {
margin : 1em 0 .2em 0;
}
form label.cCheck input {
vertical-align : text-bottom;
}
form output {
font-size : 1.4em;
font-weight : bold;
text-align : center;
background : lightblue;
padding : .3em;
box-sizing : border-box;
width : 100%;
margin : .3em 0;
}
<form name="my-form">
<fieldset>
<legend>round hole</legend>
<label class="backLinePlus cVal">
<span>Diameter :</span>
<input name="diameter-round" type="number" value="0" min="0" step="any" >
</label>
<label class="backLinePlus cVal">
<span>Metal Thickness :</span>
<input name="thickness-round" type="number" value="0" min="0" step="any" >
</label>
<h5 class="backLine">Select Metal</h5>
<label class=" cCheck backLine">
<input name="metal-round" value="al" type="radio" checked >
<span>Alum</span>
</label>
<label class="cCheck backLine">
<input name="metal-round" value="mm" type="radio" >
<span>Mild Metal</span>
</label>
<label class="cCheck backLine">
<input name="metal-round" value="hm" type="radio" >
<span>Heavy Metal</span>
</label>
<h5 class="backLine"> </h5>
<button type="button" name="bt-control-round" class="backLine">⚙ calc</button>
<output name="out-control-round" class="backLine">...</output>
</fieldset>
<fieldset>
<legend>rectangle hole</legend>
<label class="backLinePlus cVal">
<span>length :</span>
<input name="length-rect" type="number" value="0" min="0" step="any">
</label>
<label class="backLinePlus cVal">
<span>width :</span>
<input name="width-rect" type="number" value="0" min="0" step="any" >
</label>
<label class="backLinePlus cVal">
<span>Metal Thickness :</span>
<input name="thickness-rect" type="number" value="0" min="0" step="any" >
</label>
<h5 class="backLine">Select Metal</h5>
<label class=" cCheck backLine">
<input name="metal-rect" value="al" type="radio" checked >
<span>Alum</span>
</label>
<label class="cCheck backLine">
<input name="metal-rect" value="mm" type="radio" >
<span>Mild Metal</span>
</label>
<label class="cCheck backLine">
<input name="metal-rect" value="hm" type="radio" >
<span>Heavy Metal</span>
</label>
<h5 class="backLine"> </h5>
<button type="button" name="bt-control-rect" class="backLine">❏ calc</button>
<output name="out-control-rect" class="backLine">...</output>
</fieldset>
</form>

Javascript error in getting values from checkboxes

I'm not able to get the value from my checkboxes when each of them is selected alone (i.e. in isolation), except for the last one which works fine.
Could anyone help me figure this out and correct my code?
function showChoices() {
var values = [];
var cbs = document.catalog.colors;
for (var i = 0, cbLen = cbs.length; i < cbLen; i++) {
if (cbs[i].checked) {
values.push(cbs[i].value);
document.getElementById('display').innerHTML = "You selected: " + values.join(', ') + ".";
} else {
document.getElementById('display').innerHTML = "Please select an option.";
}
}
}
<form method="post" name="catalog">
<input type="checkbox" name="colors" value="red" /><span>red</span> <br />
<input type="checkbox" name="colors" value="orange" /><span>orange</span> <br />
<input type="checkbox" name="colors" value="green" /><span>green</span> <br />
<input type="checkbox" name="colors" value="blue" /><span>blue</span> <br />
<input type="button" onclick="showChoices();" value="Submit">
</form>
<br />
<span id='display'></span>
Working Solution
You can write js like this and hope this helps:
function showChoices() {
var values = [];
var cbs = document.catalog.colors;
var cbLen = cbs.length;
for (var i = 0; i < cbLen; i++) {
if (cbs[i].checked) {
values.push(cbs[i].value);
}
}
if (values.length != 0) {
document.getElementById('display').innerHTML = "You selected: " + values.join(', ') + ".";
} else {
document.getElementById('display').innerHTML = "Please select an option.";
}
}
<form method="post" name="catalog">
<input type="checkbox" name="colors" value="red" /><span>red</span> <br />
<input type="checkbox" name="colors" value="orange" /><span>orange</span> <br />
<input type="checkbox" name="colors" value="green" /><span>green</span> <br />
<input type="checkbox" name="colors" value="blue" /><span>blue</span> <br />
<input type="button" onclick="showChoices();" value="Submit">
</form>
<br />
<span id='display'></span>
You are overriding the div#display's innerHTML with the "Please select an option..." text whenever the last iteration of your loop jumps into the else block (meaning the last box isn't checked).
I would check if at least one element is selected, and if not return early from your function. After that, you can simply display the values by joining them together.
function showChoices() {
var values = [];
var cbs = Array.from(document.catalog.colors);
let el = document.getElementById('display');
let checked = cbs.filter(e => e.checked);
if (!checked.length) {
el.innerHTML = 'Please select at least one';
return false;
}
el.innerHTML = `You selected ${checked.map(e => e.value).join(', ')}`;
return false;
}
<form method="post" name="catalog">
<input type="checkbox" name="colors" value="red" /><span>red</span> <br />
<input type="checkbox" name="colors" value="orange" /><span>orange</span> <br />
<input type="checkbox" name="colors" value="green" /><span>green</span> <br />
<input type="checkbox" name="colors" value="blue" /><span>blue</span> <br />
<input type="button" onclick="showChoices();" value="Submit">
</form>
<br />
<span id='display'></span>

I am building multiple checkboxes. I want to add the functionality

I am building multiple checkboxes. I want to add the functionality, where in a group one checkbox only one checkbox should checked with right or wrong value. After selecting all the groups submit button should be enables.After clicking on submit button, value of each group should (right or wrong answer) should be displayed.How should I go about doing that ?
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" />
As specified in the comments you can use RadioButton instead of Checkbox this will handle for your the checking stuffs. However, to enable the submit button you have to do some maths, by verifying if the number of the checked radio buttons is the half of the total number of the radio buttons:
if($("input[type='radio']").length/2==$("input[type='radio']:checked").length)
{
$(".btn").prop("disabled","");
}
Finally, here is a demo:
$("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"/>
<FORM NAME=MAIN>
<SCRIPT>
HTML = [];
function PRINT(L, X) { HTML.push(L.split("#").join(X)); }
function FLUSH() { document.write(HTML.join("")); HTML = []; }
COOKIE = "ANSWERS";
function SetCookie(NAME, VALUE) { var E = new Date(); E.setFullYear(E.getFullYear() + 5); document.cookie = NAME + "=" + VALUE + ";Expires=" + E.toGMTString(); }
function GetCookie(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 = "0033CC";
TEXT_COLOR = "FFFFFF";
ROW_COLORS = "111133 333355".split(" ");
Q = "Do you speak English?|Do you have an Apple iPhone X ?|Do you write JavaScript?|Have you ever caught an alligator?|Did you eat it?|Do you like winter?|Is the earth big?|Zero equals false. Agree?|Does your laptop run on 19 volts?".split("|");
ANSWER = GetCookie(COOKIE);
if (ANSWER && ANSWER != null) ANSWER = ANSWER.split(","); else ANSWER = [];
for (i = ANSWER.length; i < Q.length; i++) ANSWER.push(0);
PRINT("<TABLE CELLSPACING=1 CELLPADDING=7 BGCOLOR=#>", BOX_COLOR);
PRINT("<TR><TD>#True<TD>#False<TD>#Questions", "<FONT COLOR=" + TEXT_COLOR + ">");
for (i = 0; i < Q.length; i++)
{
PRINT("<TR BGCOLOR=#>", ROW_COLORS[i&1]);
PRINT("<TD><CENTER><INPUT "+(ANSWER[i]==1?"CHECKED":"")+" NAME=X#A TYPE=CHECKBOX onClick='K(#, 1);'>", i);
PRINT("<TD><CENTER><INPUT "+(ANSWER[i]==2?"CHECKED":"")+" NAME=X#B TYPE=CHECKBOX onClick='K(#, 2);'>", i);
PRINT("<TD onClick='K(#, 0);'><FONT COLOR="+TEXT_COLOR+">"+(i+1)+". " + Q[i], i);
}
PRINT("</TABLE><P>");
PRINT("<INPUT TYPE=BUTTON VALUE=' Get Answers ' onClick='alert(ANSWER);'>");
PRINT("<INPUT TYPE=BUTTON VALUE=' Delete Answers ' onClick='DeleteAnswers();'>");
PRINT("<INPUT TYPE=BUTTON "+(isComplete()?"":"DISABLED")+" NAME=NEXT VALUE=' NEXT ' onClick='Next();' onMouseOver='CheckAnswers();'>");
FLUSH();
function K(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;");
CheckAnswers();
SaveAnswers();
}
function isComplete() { for (var i = 0; i < Q.length; i++) if (ANSWER[i] == 0) return 0; return 1; }
function AllowNext() { document.MAIN.NEXT.disabled = false; }
function CheckAnswers() { if (isComplete()) AllowNext(); }
function Next() { location.href = "http://www.msn.com"; }
function SaveAnswers() { SetCookie(COOKIE, ANSWER.join(",")); }
function DeleteAnswers()
{
for (var i = 0; i < Q.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;
SetCookie(COOKIE, "");
}
</SCRIPT>

How Do I count the selected checkbox in AngularJS?

/**
* #Summary: checkAllConnectedUser function, to create album
* #param: index, productObj
* #return: callback(response)
* #Description:
*/
$scope.shardBuyerKeyIdArray = [];
$scope.countBuyer = 0;
$scope.checkAllSharedBuyer = function(isChecked) {
if (isChecked) {
if ($scope.selectAll) {
$scope.selectAll = false;
} else {
$scope.selectAll = true;
}
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
//IF ID WILL BE EXIST IN THE ARRAY NOT PSUH THE KEYID
if ($scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId) == -1) {
$scope.shardBuyerKeyIdArray.push(selectedBuyer.userTypeDto.keyId);
$scope.countBuyer++;
}
});
} else {
$scope.selectAll = false;
//USED FOR UNCHECK ALL THE DATA ONE- BY-ONE
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
var index = $scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId);
$scope.shardBuyerKeyIdArray.splice(index, 1);
$scope.countBuyer--;
});
}
}
<div class="checkbox w3-margin" ng-if="selectedSharedBuyerObjectList.length > 0">
<span class="w3-right" ng-if="countBuyer">
<h5>You are selecting {{countBuyer}} buyers!</h5>
</span>
<label>
<input type="checkbox" ng-model="selectAll" ng-click="checkAllSharedBuyer(selectAll)"/>Check All
</label>
</div>
<div id="sharedRow" class="checkbox" ng-repeat="selectedBuyer in cmnBuyer = (selectedSharedBuyerObjectList | filter : userSearchInProduct
| filter : filterUser)">
<label>
<input type="checkbox" ng-model="selectedBuyer.select"
ng-change="selectedSharedBuyer($index, selectedBuyer.select, selectedBuyer.userTypeDto.keyId)"/>
{{selectedBuyer.personName}}
</label>
</div>
I have two list in which i have to count the select all checkbox length as well as single checkbox count my problem if the user un-check the ALL checkbox Checkbox count will be return -- what's the problem in my code?
$(function(){
var count = 0;
$('#sharedRow ').find('input[type=checkbox]').on('change',function(){
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
})
$('#chkAll').on('change', function () {
if ($(this).is(':checked')) {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', true);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
else {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', false);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox w3-margin">
<span class="w3-right">
<h5 id="msg" >You are selecting 0 buyers!</h5>
</span>
<label>
<input id="chkAll" type="checkbox" />Check All
</label>
</div>
<div id="sharedRow" class="checkbox">
<label>
<input type="checkbox" value="1 Buyers" />1 Buyers
</label>
<label>
<input type="checkbox" value="2 Buyers" />2 Buyers
</label>
<label>
<input type="checkbox" value="3 Buyers" />3 Buyers
</label>
<label>
<input type="checkbox" value="4 Buyers" />4 Buyers
</label>
<label>
<input type="checkbox" value="5 Buyers" />5 Buyers
</label>
<label>
<input type="checkbox" value="6 Buyers" />6 Buyers
</label>
<label>
<input type="checkbox" value="7 Buyers" />7 Buyers
</label>
<label>
<input type="checkbox" value="8 Buyers" />8 Buyers
</label>
</div>
try this one. is it ok? if not then tell me what's wrong.
if you have a group of checkbox then you can find all selected checkbox.
$('div').find('input[type=checkbox]:checked').length;
If you only need the number
var count = $scope.selectedSharedBuyerObjectList.reduce(function(sum, item) {
return (item.select) ? sum + 1 : sum;
}, 0);
If you need the filtered array
var selected = $scope.selectedSharedBuyerObjectList.filter(function(item) {
return item.select;
});
var count = selected.length;
Or do it using plain old loop
var count = 0;
for (i = 0; i < $scope.selectedSharedBuyerObjectList.length; i++) {
if ($scope.selectedSharedBuyerObjectList.select) count++;
}

Validation for dynamic radio button,checkbox and text area

I have developed one page,which is contains several questions and answer...there are three types of answer radio button,checkbox and text area... i have to validate these dynamically created questions using javascript...
based on the question type i am getting answer options from database whether it may be a radio button or checkbox or text area...
<input type="radio" id="radio" name="21" value="59"/>
<input type="radio" id="radio" name="22" value="60"/>
<input type="radio" id="radio" name="23" value="61"/>
like same as checkbox and text area....
//try 1
var form = document.getElementById('form1');
var inputs = form.getElementsByTagName('INPUT');
for (var i = 0; i < inputs.length; ++i) {
if (inputs[i].type.toLowerCase == 'radio' && !inputs[i].checked)
return false;
}
return true;
//try 2
var rv = document.getElementsByName("reservation_in");
var ci = -1;
for(var ikj=0; ikj < rv.length; ikj++){
if(rv[ikj].checked) {
ci = ikj;
}
}
if (ci == -1) {
document.getElementById('err_reservation_for').innerHTML="";
document.getElementById('err_reservation_for').innerHTML=
'Please let us know
//Reservation for Inside or Patio.';
return false;
}
//try 3
var radios = document.getElementById('radio');
var formValid = false;
var i = 0;
while (!formValid && i < radios.length) {
if (radios[i].checked)
formValid = true;
i++;
}
if (!formValid)
//document.getElementById('radio_error').innerHTML="";
//document.getElementById('radio_error').innerHTML=
'Please select one answer.';
alert("Please select the answer");
return formValid;
I have some sample code which may help you to understand more.
HTML Code:
<div id="que1" class="que">
xyz is not abc? <br />
<div class="ans">
<input type="radio" name="radioGroup1" id="radio1" />One
<input type="radio" name="radioGroup1" id="radio2" />Two
<input type="checkbox" name="check" id="check1" />Three <br/>
<textarea id="textarea-1"></textarea>
</div>
</div><br />
<div id="que2" class="que">
xyz is not abc? <br />
<div class="ans">
<input type="radio" name="radioGroup2" id="radio3" />One
<input type="radio" name="radioGroup2" id="radio3" />Two
<input type="checkbox" name="check" id="check2" />Three <br />
<textarea id="textarea-2"></textarea>
</div>
</div>
JS Code:
var questions=document.getElementsByClassName("que");
for(var i=0;i<questions.length;i++){
var inputs=questions[i].getElementsByTagName("input");
for(var j=0;j<inputs.length;j++){
if(inputs[j].type=="radio"){
alert("question ID:- "+ questions[i].id+ " radio");
}
if(inputs[j].type=="checkbox"){
alert("question ID:- "+ questions[i].id+ " checkbox");
}
}
var textarea=questions[i].getElementsByTagName("textarea");
for(var k=0;k<textarea.length;k++){
alert("question ID:- "+ questions[i].id+ " Textarea");
}
}
Click here check this fiddle
Radio button validation:
Html:
<form>
<input type="radio" id="21" name="radio" value="59"/>
<input type="radio" id="22" name="radio" value="60"/>
<input type="radio" id="23" name="radio" value="61"/>
</form>
Javascript:
if ( ( form.radio[0].checked == false ) && ( form.radio[1].checked == false ) && ( form.radio[2].checked == false ) ) { alert ( "Please choose one radio button" ); return false; }
If there are many input box then use each..that will iterate just like for loop..
var iz_checked = false;
var is_blank = false;
var is_choose = false;
$('button').on('click', function() {
iz_checked = false;
is_blank = false;
is_choose = false;
$('input[type="radio"]').each(function() {
if ($('input[type="radio"]').is(':checked') == true) {
iz_checked = false;
} else {
iz_checked = true;
}
if ($('textarea')[0].value == "") {
is_blank = true;
}
});
$('input[type="checkbox"]').each(function() {
if ($('input[type="checkbox"]').is(':checked') == true) {
is_choose = false;
} else {
is_choose = true;
}
});
if (is_choose || iz_checked || is_blank) {
alert("Validation err");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input type="radio" id="21" value="59" />a
<input type="radio" id="22" value="60" />q
<input type="radio" id="23" value="61" />w
<input type="radio" id="1" value="59" />e
<input type="radio" id="2" value="60" />r
<input type="radio" id="3" value="61" />t
<input type="radio" id="29" value="59" />y
<input type="radio" id="80" value="60" />u
<input type="radio" id="7" value="61" />i
<input type="radio" id="8" value="59" />o
<input type="radio" id="0" value="60" />p
<input type="radio" id="1" value="61" />l
</form>
<textarea cols="10" rows="10"></textarea>
<br/>
<input type="checkbox" value="Apples">f
<input type="checkbox" value="Apples">d
<input type="checkbox" value="Apples">s
<input type="checkbox" value="Apples">a
<br/>
<button>
Validate
</button>

Categories

Resources