I want to check if any checkbox on the website has been checked when text has been entered in the name text box. I know that the EventListener works for name since this works without the document.getElementsByName("event[]").checked, but how do I make it work for the checkboxes?
document.getElementsByName("name")[0].addEventListener('change', (event) => {
if (event.target.value.length != 0 && document.getElementsByName("event[]").checked ) {
window.alert("checked");
}
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="Events">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1</span>
<span class='eventPrice'>10.50</span>
<span class='chosen'><input type='checkbox' name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2</span>
<span class='eventPrice'>5.00</span>
<span class='chosen'><input type='checkbox' name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<input type="radio" name="delivery" value="ticket" data-price="10">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
<p>Name<input type="text" name="name"></p>
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
I'd suggest:
document.getElementsByName("name")[0].addEventListener('change', (event) => {
// here we used event.target.value.trim.length in order to guard against
// white-space strings being considered valid (if that's not a problem
// then the trim() method can be removed), and also we used:
// document.querySelector() to find the first of any <input> element
// with a type equal to 'checkbox' which is also checked;
// document.querySelector() returns either the first such element or null:
if (event.target.value.trim().length > 0 &&
document.querySelector('input[type=checkbox]:checked') !== null) {
window.alert("checked");
}
});
document.getElementsByName("name")[0].addEventListener('change', (event) => {
if (event.target.value.trim().length > 0 &&
document.querySelector('input[type=checkbox]:checked') !== null) {
window.alert("checked");
}
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="Events">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1</span>
<span class='eventPrice'>10.50</span>
<span class='chosen'><input type='checkbox' name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2</span>
<span class='eventPrice'>5.00</span>
<span class='chosen'><input type='checkbox' name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<input type="radio" name="delivery" value="ticket" data-price="10">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
<p>Name<input type="text" name="name"></p>
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
It's worth adding that your first line could be potentially simplified a little using document.querySelector() rather than using indices:
document.querySelector("input[name=name]").addEventListener('change', (event) => {
if (event.target.value.trim().length > 0 &&
document.querySelector('input[type=checkbox]:checked') !== null) {
window.alert("checked");
}
});
document.querySelector('input[name=name]').addEventListener('change', (event) => {
if (event.target.value.trim().length > 0 &&
document.querySelector('input[type=checkbox]:checked') !== null) {
window.alert("checked");
}
});
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="Events">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1</span>
<span class='eventPrice'>10.50</span>
<span class='chosen'><input type='checkbox' name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2</span>
<span class='eventPrice'>5.00</span>
<span class='chosen'><input type='checkbox' name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<input type="radio" name="delivery" value="ticket" data-price="10">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
<p>Name<input type="text" name="name"></p>
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
References:
CSS:
Attribute-selectors ([attribute=attribute-value]).
:checked.
JavaScript:
document.querySelector().
String.prototype.trim()
//--Get all checkboxes, you can have another way of fetching checkboxes
var checkBoxes = document.getElementsByTagName("input");
//--For each checkbox, check if it is selected
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked == true) {
alert('checked');
}
}
Use document.querySelectorAll to get an array containing all the checkbox inputs in the document:
var checkboxes = document.querySelectorAll("input[type=checkbox]");
Then, to check if any of the checkboxes are checked:
var anyChecked = false;
for (var i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
anyChecked = true;
break;
}
}
Alternatively, if you want an array containing only the checkboxes that are checked, you can do the following:
var checkedCheckboxes = checkboxes.filter(checkbox => checkbox.checked);
document.getElementsByName("name")[0].addEventListener('change', (event) => {
if(event.target.value.length !== 0) {
// Get all checkboxes
const checkboxes = document.getElementsByName("event[]");
for(i=0; i<checkboxes.length; i++) {
// Check if checkbox is checked or not
if(checkboxes[i].checked) {
window.alert("checked");
}
}
}
})
Related
I have a query selector for checkboxes which works fine and I replicated it for radio button, but I am running into the problem that they are both keeping separate totals. I tried to take the totalPrice variable out of both of them and place it outside so that it would be shared, but that created the problem of the price not being removed from unchecked checkboxes and radio buttons.
This is my current buggy code:
const form = document.getElementById('bookingForm');
const total = document.getElementById('total');
document.getElementById("bookingForm").addEventListener("click", function(e) {
if (e.target.name === "event[]") {
let totalprice = 0;
[...document.querySelectorAll('input[data-price][type=checkbox]')].forEach(function(box) {
if (box.checked) {
totalprice += +box.dataset.price;
}
})
document.querySelector("[name=total]").value = totalprice.toFixed(2);
}
})
document.getElementById("bookingForm").addEventListener("click", function(e) {
if (e.target.name === "delivery") {
let totalprice = 0;
[...document.querySelectorAll('input[data-price][type=radio]')].forEach(function(box) {
if (box.checked) {
totalprice += +box.dataset.price;
}
})
document.querySelector("[name=total]").value = totalprice.toFixed(2);
}
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1</span>
<span class='eventPrice'>10.50</span>
<span class='chosen'><input type='checkbox' name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2</span>
<span class='eventPrice'>5.00</span>
<span class='chosen'><input type='checkbox' name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<input type="radio" name="delivery" value="ticket" data-price="10">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
Just have one event handler and one loop
If you only have data-price on the elements you need to loop, then you can change
[...document.querySelectorAll('input[data-price][type=checkbox], input[data-price][type=radio]')].forEach(function(box) {
to
[...document.querySelectorAll('input[data-price]')].forEach(function(box) {
I just wonder why you have a only a single radio - it cannot be un-selected. Why not another checkbox?
const form = document.getElementById('bookingForm');
const total = document.getElementById('total');
form.addEventListener("click", function(e) {
if (e.target.name === "event[]" || e.target.name === "delivery") {
let totalprice = 0;
[...document.querySelectorAll('input[data-price][type=checkbox], input[data-price][type=radio]')].forEach(function(box) {
if (box.checked) {
totalprice += +box.dataset.price;
}
})
document.querySelector("[name=total]").value = totalprice.toFixed(2);
}
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1</span>
<span class='eventPrice'>10.50</span>
<span class='chosen'><input type='checkbox' name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2</span>
<span class='eventPrice'>5.00</span>
<span class='chosen'><input type='checkbox' name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<input type="radio" name="delivery" value="ticket" data-price="10">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
My goal is when a checkbox is clicked it's data-price should be added to the total variable and then this variable should be shown in the total price text box, however, it currently doesn't update the value when a checkbox is clicked.
Here is an interactive example of how it currently works/looks:
const form = document.getElementById('bookingForm');
const total = document.getElementsByName[0]('total');
document.getElementById("bookingForm").addEventListener("click", function(e) {
if (e.target.name === "event[]") {
let total = 0;
[...document.querySelectorAll('input[data-price][type=checkbox]')].forEach(function(box) {
if (box.checked) {
total += +box.dataset.price;
} //if
})
document.querySelector("[name=total]").innerHTML = total.toFixed(2);
}
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1</span>
<span class='eventPrice'>10.50</span>
<span class='chosen'><input type='checkbox' name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2</span>
<span class='eventPrice'>5.00</span>
<span class='chosen'><input type='checkbox' name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
const form = document.getElementById('bookingForm');
const total = document.getElementsByName('total');
var chksBoxes = document.querySelectorAll('.chkEvent');
chksBoxes.forEach(function(chk) {
chk.addEventListener("click", function(e) {
var total = 0;
chksBoxes.forEach(function(box) {
if (box.checked)
total += +box.dataset.price
});
document.querySelector("[name=total]").value = total.toFixed(2);
});
});
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1 </span>
<span class='eventPrice'>Price: 10.50</span>
<span class='chosen'><input type='checkbox' class="chkEvent" name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2 </span>
<span class='eventPrice'>Price: 5.00</span>
<span class='chosen'><input type='checkbox' class="chkEvent" name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
For Input elements you should use value instead of innerHTML
const form = document.getElementById('bookingForm');
const total = document.getElementsByName('total')[0];
document.getElementById("bookingForm").addEventListener("click", function(e) {
if (e.target.name === "event[]") {
let total = 0;
[...document.querySelectorAll('input[data-price][type=checkbox]')].forEach(function(box) {
if (box.checked) {
total += +box.dataset.price;
} //if
})
document.querySelector("[name=total]").value = total.toFixed(2);
}
})
<form id="bookingForm" action="javascript:alert('form submitted');" method="get">
<section id="bookEvents">
<h2>Select Events</h2>
<div class='item'>
<span class='eventTitle'>Event number 1</span>
<span class='eventPrice'>10.50</span>
<span class='chosen'><input type='checkbox' name='event[]' value='1' data-price='10.50'></span>
</div>
<div class='item'>
<span class='eventTitle'>Event number 2</span>
<span class='eventPrice'>5.00</span>
<span class='chosen'><input type='checkbox' name='event[]' value='2' data-price='5.00'></span>
</div>
<section id="Cost">
<h2>Total Price</h2>
Total Price <input type="text" name="total" size="12">
</section>
<p><input type="submit" name="submit" value="Book"></p>
</section>
</form>
PS: You have a typo at line# 2 where document.getElementsByName[0]('total'); should actually be document.getElementsByName('total')[0];
When I click on the checkbox at the top, it puts a '0' in the total box, so I know that it is connected correctly, however I think there is a problem in the logic in the loop. One of the elements in html looks like this.
const form = document.getElementById('bookingForm');
const total = document.getElementById('total');
const checkboxes = document.querySelectorAll('input[data-price][type=checkbox]');
const cbamount = checkboxes.length;
document.getElementsByName('event[]')[0].onclick = function() {
totalPrice()
};
function totalPrice() {
let totalprice = 0;
for (let i = 0; i < cbamount; i++) {
const box = checkboxes[i];
if (box.checked) {
box.dataset.price = totalprice + box.dataset.price;
} //if
} //for
document.getElementsByName("total")[0].value = totalprice;
}
<span class="eventTitle">Carmen </span>
<span class="eventStartDate">2020</span>
<span class="eventEndDate">2020</span>
<span class="catDesc">T</span>
<span class="venueName">Mill </span>
<span class="eventPrice">3</span>
<span class="chosen"><input type="checkbox" name="event[]" value="11" data-price="35.00"></span>
<section id="Cost">
<h3>Total</h3>
Total <input type="text" name="total" size="20" readonly="">
</section>
You have no total in the code you provided.
I would personally use ID when only having one element and if more, use relative addressing and/or delegation
const form = document.getElementById('booking');
const total = document.getElementById('total');
document.getElementById("booking").addEventListener("click", function(e) {
if (e.target.name === "event[]") {
let totalprice = 0;
[...document.querySelectorAll('input[data-price][type=checkbox]')].forEach(function(box) {
if (box.checked) {
totalprice += +box.dataset.price;
} //if
})
document.querySelector("[name=total]").value = totalprice.toFixed(2);
}
})
<form id="booking" method="get">
<section id="book">
<h2>Select Events</h2>
<div class="item">
<span class="eventTitle">Carmen </span>
<span class="eventStartDate">2020</span>
<span class="eventEndDate">2020</span>
<span class="catDesc">T</span>
<span class="venueName">Mill </span>
<span class="eventPrice">3</span>
<span class="chosen"><input name="event[]" type="checkbox" value="11" data-price="35.00"></span>
</div>
<div class="item">
<span class="eventTitle">Ash</span>
<span class="eventStartDate">202</span>
<span class="eventEnd">2020-12-31</span>
<span class="catD">Exhib</span>
<span class="venueNa">The Biy</span>
<span class="eventPr">0.00</span>
<span class="chosen"><input type="checkbox" name="event[]" value="17" data-price="10.00"></span>
</div>
</section>
<section id="Cost">
<h3>Total</h3>
Total <input type="text" name="total" size="20" readonly="">
</section>
</form>
I record meals in this way, as I show in the image:
I created the Apply to All button, which is to fill the remaining days of the month with the same data after completing the 1st of the month. For example:
I pre-pack the day 1:
By clicking the Apply to All button fill the remaining days in the same way:
Code:
<input type='button' id='elemento' value='Aplicar a Todos' />
<td bgcolor='$color' data-semana=''><font size='2px'/>
<input id='firstCB{$year}{$month}{$day}' type='checkbox' name='arrachar[$year, $month, $day][dia]' value='$year-$month-$day'>$year-$month-$day <br />
<div>
<input type='checkbox' class='checkbox' name='arrachar[$year, $month, $day][OpcaoA]' value='Peq_Almoço'>Peq. Almoço</div> <div><input ref='firstCB{$year}{$month}{$day}' min='0' oninput='this.value = Math.abs(this.value)' type='number' name='arrachar[$year, $month, $day][Qtd]' value='$marcado_pequeno_qtd' />
<br />
</div>
<div>
<input type='checkbox' class='checkbox1' name='arrachar[$year, $month, $day][opcaoB]' value='Almoço'>Almoço</div> <div><input ref='firstCB{$year}{$month}{$day}' min='0' oninput='this.value = Math.abs(this.value)' type='number' name='arrachar[$year, $month, $day][Qtd1]' value='$marcado_almoco_qtd'/>
<br />
</div>
</td>
Javascript:
$('#elemento').on('click', function(){
var inputs = [...document.querySelectorAll("[type='checkbox']")];
if(inputs == 'checked'){ // condição
$('.checkbox').prop('checked', true);
$('.checkbox1').prop('checked', true);
}
});
I wanted you to select all the checkboxes on every day as on day 1 and also fill in the inputs with the same value as day 1.
As I have the condition does not select any checkbox when clicking the Apply to all button.
I know you are using JQuery, but heres an option in vanilla JS. Talvez te servia melhor. Portugal Ale!
const dayChecks = document.querySelectorAll('.day input[type="checkbox"]');
const dayInputs = document.querySelectorAll('.day input[type="number"]');
const btn = document.querySelector('#click');
btn.addEventListener('click', () => {
dayChecks.forEach( input => { // Handles checkboxes
if(input.checked){
const elClass = input.parentElement.getAttribute('class');
const allEls = document.querySelectorAll(`.${elClass}`);
allEls.forEach( (el) => {
el.querySelector('input[type="checkbox"]').setAttribute('checked', 'checked');
});
}
});
dayInputs.forEach( input => { // Handles Inputs
if(input.value != ''){
const value = input.value;
const elClass = input.parentElement.getAttribute('class');
const allEls = document.querySelectorAll(`.${elClass}`);
allEls.forEach( (el) => {
el.querySelector('input[type="number"]').value = value;
});
}
});
});
.week {
display: flex;
flex-direction: row;
}
.day{
padding: 20px;
}
<button id='click'>Apply to All</button>
<div class="week">
<div class="day">
<h2>Primeiro Dia</h2>
<div class="peqAlmoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="almoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="jantar">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
</div>
<div class="day">
<h2>Segundo Dia</h2>
<div class="peqAlmoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="almoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="jantar">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
</div>
<div class="day">
<h2>Terçeiro Dia</h2>
<div class="peqAlmoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="almoco">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
<div class="jantar">
<input type="checkbox" name="" value="">
<input type="number" value="">
</div>
</div>
</div>
If you want an elegant JQuery implementation try this:
$(document).ready(function(){
// used the first checkbox (input with the date class) to select each data column for entering data
// this is the column you want replicated on other columns
$('.date').change(function() {
// inactivate every other column that is not this column
$('.date').not($(this)).prop('checked', false).parents('td').removeClass('active');
// show that this is the currently selected column
$(this).parents('td').toggleClass('active');
});
// click handler for 'apply to all' button
$('#elemento').click(function() {
var checkboxstate = {}; // object to store all the checkbox state in the current column
var numberstate = {}; // object to store content of all text input in the current column
// for each input element in the active column
$.each($('.active').find('input'), function(key, element){
if($(this).prop('type') == 'checkbox') {
// collect all checkbox state
checkboxstate[element.name] = $(this).prop('checked');
} else {
// collect all input text content
numberstate[element.name] = $(this).val();
}
});
// for each checkbox or number
$.each($('.checkbox, .number'), function(key, element) {
// store these variables beforehand so you don't need to test for them in the inner each statement
// for checkboxes
var target = checkboxstate;
var type = 'checkbox';
var property = 'checked';
// for number elements
if($(this).is('.number')) {
target = numberstate;
type = 'number';
property = 'value';
}
// assign object properties to dom elements with same type and name properties as that of the object property
$.each(target, function(key_1, element_1) {
if($(element).prop('type') == type && $(element).prop('name') == key_1) {
$(element).prop(property, element_1);
}
});
});
return false;
});
});
<!DOCTYPE html>
<meta charset="UTF-8">
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="index.js"></script>
<title>My test doc</title>
<style>
table {
border-collapse: collapse;
}
.active {
background-color: #00ff00;
}
input {
margin-bottom: 5px;
}
.checkbox-div {
float: left;
}
.number-div {
float: right;
margin-left: 10px;
}
</style>
</head>
<body>
<h3>welcome</h3>
<form method="GET" action="#">
<table style="border-collapse: collapse">
<tr>
<td>
<input class="date" type='checkbox' name='date' value='date'>Date
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Peq_Almoço' value='Peq_Almoço'>Peq. Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Peq_Almoço' value='' />
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Almoço' value='Almoço'>Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Almoço' value=''/>
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Lanche' value='Lanche'>Lanche
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Lanche' value=''/>
</div>
<br/>
</td>
<td>
<input class="date" type='checkbox' name='date' value='date'>Date
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Peq_Almoço' value='Peq_Almoço'>Peq. Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Peq_Almoço' value='' />
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Almoço' value='Almoço'>Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Almoço' value=''/>
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Lanche' value='Lanche'>Lanche
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Lanche' value=''/>
</div>
<br/>
</td>
</tr>
<tr>
<td>
<input class="date" type='checkbox' name='date' value='date'>Date
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Peq_Almoço' value='Peq_Almoço'>Peq. Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Peq_Almoço' value='' />
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Almoço' value='Almoço'>Almoço
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Almoço' value=''/>
</div>
<br/>
<div class="checkbox-div">
<input type='checkbox' class='checkbox' name='Lanche' value='Lanche'>Lanche
</div>
<div class="number-div">
<input min='0' type='number' class='number' name='Lanche' value=''/>
</div>
<br/>
</td>
</tr>
</table>
<input type='button' id='elemento' value='Aplicar a Todos' />
</form>
</body>
</html>
Also see the Fiddle sample here
Here, each column is represented by a td element. I used the first checkbox with the date class to select the column we want other columns to replicate.
Also, the checkbox and number inputs are loosed coupled - that is, a checkbox can be unchecked with the corresponding number input filled and this will still be replicated on other columns.
Three columns were used for brevity. You can create as many columns as you want and the jQuery script will still run seamlessly.
You can apply classes to each checkbox and select all checkbox on click of Apply to All button
<input type="checkbox" class="Almoco" />
$('#elemento').on('click', function(){
if(check for your condition if you need to apply check for all checkboxes)
{
$('.Almoco').prop('checked', true);
}
//Similiarily check for other checkboxes
});
Your variable inputs is a collection of inputs, therefore you have to check the state of each input in a forEach or a for loop.
Same for other inputs that you want to modify the state.
Code:
$('#elemento').on('click', function(){
var inputs = $('td > input');
inputs.each(function(index, element){
if(element.checked) {
var children = $(element).parent().find('input[type="checkbox"]');
children.each(function(i, child){
$(child).prop('checked', true);
});
}
});
});
I was able to solve the problem of applying to everyone in the following way:
$('#elemento').click(function() {
var checkedValues = Array(8).fill(false);
var textValues = Array(7).fill('');
var checkedStep = 0;
var textStep = 0;
$('tr').find('input[type="checkbox"]').each(function(index, value){
if(index < 8){
checkedValues[index] = $(this).prop("checked");
}else{
if(checkedStep == 8){
checkedStep = 0;
}
$(this).prop('checked', checkedValues[checkedStep++]);
}
});
$('tr').find('input[type="number"]').each(function(index, value){
if(index < 7){
textValues[index] = $(this).val();
}else{
if(textStep == 7){
textStep = 0;
}
$(this).val(textValues[textStep++]);
}
});
});
$("#button").click(function () {
var pp = []
var ing = []
for (var q = 1; q <= 6; q++) {
pp[q - 1] = $('input[name=P' + (q) + ']').is(":checked");
ing[q - 1] = $('div#ingp' + (q) + '').show();
}
for (var q = 1; q <= 6; q++) {
if (pp[q - 1] == true) {
ing[q - 1];
}
}
});
<div class="Pizzas container" id="checkbox_pizza">
<h1>Kies uw Pizza.</h1>
<form id="Pi">
<input type="checkbox" name="P1" id="g"> €6,00 -Margherita (Kaas en tomaten)
<br/>
<input type="checkbox" name="P2" id="h"> €7,20 -Napolitana (tomaten, kaas, kappertjes, ansjovis)
<br/>
<input type="checkbox" name="P3" id="i"> €7,50 -Salami (kaas, tomaten en salami)
<br/>
<input type="checkbox" name="P4" id="j"> €7,50 -Prosciutto (tomaten, kaas, ham)
<br/>
<input type="checkbox" name="P5" id="k"> €7,00 -Funghi (tomaten, kaas, champions)
<br/>
<input type="checkbox" name="P6" id="l"> €8,00 -Tonno (tomaten, kaas, tonijn, ui)
<br/>
<input type="button" id="knop" value="button" />
</form>
</div>
<div class="container" id="Boxx">
<div id="ingrediënten">
<div>
<h1>Kies extra ingredienten</h1>
</div>
<div id="ingp1"></div>
<div id="ingp2"></div>
<div id="ingp3"></div>
<div id="ingp4"></div>
<div id="ingp5"></div>
<div id="ingp6"></div>
<input type="button" id="knop2" value="Totaal" />
</div>
</div>
So the problem I have is that when I look if one or more of P1 to P6 is check then it shows all 6 div with id ingp1 to ingp6.
I want it to show ingp1 when P1 is checked, and ingp3 when P3 is checked. You get it.
How do I do this (small thing I am only allowed to use javascript and jquery).
First of all add a common class names for the elements in the form and the div's in the container as I have given test1,test2 etc.
$('document').ready(function() {
var test
$("#Pi input[ type = 'checkbox']").click(function() {
var test = this.className
if ( this.checked == true )
{
$('#ingredienten .'+test).show()
console.log($('#ingrediënten .'+test))
}
else
{
$('#ingrediënten .'+test).hide()
}
})
})
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.js" integrity="sha256-Qw82+bXyGq6MydymqBxNPYTaUXXq7c8v3CwiYwLLNXU=" crossorigin="anonymous"></script>
</head>
<body>
<div class="Pizzas container" id="checkbox_pizza">
<h1>Kies uw Pizza.</h1>
<form id="Pi">
<input type="checkbox" class = "test1" name="P1" id="g"> €6,00 -Margherita (Kaas en tomaten)
<br/>
<input type="checkbox" class = "test2" name="P2" id="h"> €7,20 -Napolitana (tomaten, kaas, kappertjes, ansjovis)
<br/>
<input type="checkbox" class = "test3" name="P3" id="i"> €7,50 -Salami (kaas, tomaten en salami)
<br/>
<input type="checkbox" class = "test4" name="P4" id="j"> €7,50 -Prosciutto (tomaten, kaas, ham)
<br/>
<input type="checkbox" class = "test5" name="P5" id="k"> €7,00 -Funghi (tomaten, kaas, champions)
<br/>
<input type="checkbox" class = "test6" name="P6" id="l"> €8,00 -Tonno (tomaten, kaas, tonijn, ui)
<br/>
<input type="button" id="knop" value="button" />
</form>
</div>
<div class="container" id="Boxx">
<div id="ingredienten">
<div>
<h1>Kies extra ingredienten</h1></div>
<div id="ingp1" class = "test1">
</div>
<div id="ingp2" class = "test2">
</div>
<div id="ingp3" class = "test3">
</div>
<div id="ingp4" class = "test4">
</div>
<div id="ingp5" class = "test5">
</div>
<div id="ingp6" class = "test6">
</div>
<input type="button" id="knop2" value="Totaal" />
</div>
</div>
</body>
<html>
Then take the class name of the clicked check-box and search the div with the class name of this check-box and show or hide the div depending on its checked property.
try this
for (var q = 1; q <= 6; q++)
{
if ( $( 'input[ name = "P' + q + '"]').is(":checked") )
{
$( 'div#ingp' + q ).show();
}
}
$("#button").click(function () {
$('input[name^=P]').each(function () {
var idx = this.name.replace('P', '');
$('div#ingp' + idx).toggle(this.checked);
});
});
In words
for each <input> whose name starts with 'P',
find the associated <div> with the proper ID
toggle its visibility based on whether the <input> is checked or not
#Ttech thanks for clarifying the SO to me. Here's my solution. I slightly changed the markup in the part concerning the ids of the extra ingredients section (the divs).
Please, check my working example and see if this is what you need.
$('#ingrediënten div').hide();
$('#knop').on('click', function() {
$('#ingrediënten div').hide();
var $checkedOptions = $('#Pi input[type=checkbox]').filter(':checked'),
$extraIngredients = $('#ingrediënten div');
$checkedOptions.each(function() {
var id = $(this).attr('name');
$extraIngredients.filter('[id=' + id + ']').show();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div class="Pizzas container" id="checkbox_pizza">
<h1>Kies uw Pizza.</h1>
<form id="Pi">
<input type="checkbox" name="P1" id="g"> €6,00 -Margherita (Kaas en tomaten)
<br/>
<input type="checkbox" name="P2" id="h"> €7,20 -Napolitana (tomaten, kaas, kappertjes, ansjovis)
<br/>
<input type="checkbox" name="P3" id="i"> €7,50 -Salami (kaas, tomaten en salami)
<br/>
<input type="checkbox" name="P4" id="j"> €7,50 -Prosciutto (tomaten, kaas, ham)
<br/>
<input type="checkbox" name="P5" id="k"> €7,00 -Funghi (tomaten, kaas, champions)
<br/>
<input type="checkbox" name="P6" id="l"> €8,00 -Tonno (tomaten, kaas, tonijn, ui)
<br/>
<input type="button" id="knop" value="button" />
</form>
</div>
<div class="container" id="Boxx">
<div id="ingrediënten">
<div>
<h1>Kies extra ingredienten</h1>
</div>
<div id="P1">
Extra ingredient 1
</div>
<div id="P2">
Extra ingredient 2
</div>
<div id="P3">
Extra ingredient 3
</div>
<div id="P4">
Extra ingredient 4
</div>
<div id="P5">
Extra ingredient 5
</div>
<div id="P6">
Extra ingredient 6
</div>
<br>
<input type="button" id="knop2" value="Totaal" />
</div>
</div>