addEventListener to multiple checkboxes - javascript

Below, I have a simple form that has 4 checkboxes acting as seats. What I am trying to do is when a visitor chooses, say, seat checkboxes with IDs A2 and A4, I want those IDs and their total value to be shown instantly after clicking inside a paragraph with which have a name called id="demo". When a button [Reserve Now] has been clicked, the total value should be assigned to a variable called $TotalCost.
How can I accomplish this? Here's my code:
<!DOCTYPE html>
<html>
<body>
<h2>Please choose a seat to book</h2>
<form action="/action_page.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="$100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="$65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="$55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="$50"> $50<br>
<p id="demo">
Selected Seat(s)
<br>
<br>
Total: USD <input type="submit" value="Reserve Now">
</form>
</p>
<script>
document.getElementById("A1").addEventListener("click", displayCheck);
function displayCheck() {
document.getElementById("demo").innerHTML = ;
}
</script>
</body>
</html>

Here's one approach to setting up event listeners on checkboxes. I used document.querySelectorAll("input[type='checkbox']"); to fetch all of the checkbox elements from the DOM and a loop to add a listener to each checkbox. A selections object can keep track of which items have been checked. When a checkbox is clicked on, the item values are added to the object by key. When the checkbox is off, the item is deleted from the object. Whenever an action happens, the DOM is updated with all relevant information based on the contents of selections.
This example is just a quick sketch to give you the idea. You'll need another event listener for your submit button to handle sending the form data to your PHP script. I'll leave that as an exercise.
Note that the HTML you've provided is invalid because nesting is broken. A HTML validator can be helpful for fixing these sort of problems.
var selections = {};
var checkboxElems = document.querySelectorAll("input[type='checkbox']");
var totalElem = document.getElementById("seats-total");
var seatsElem = document.getElementById("selected-seats");
for (var i = 0; i < checkboxElems.length; i++) {
checkboxElems[i].addEventListener("click", displayCheck);
}
function displayCheck(e) {
if (e.target.checked) {
selections[e.target.id] = {
name: e.target.name,
value: e.target.value
};
}
else {
delete selections[e.target.id];
}
var result = [];
var total = 0;
for (var key in selections) {
var listItem = "<li>" + selections[key].name + " " +
selections[key].value + "</li>";
result.push(listItem);
total += parseInt(selections[key].value.substring(1));
}
totalElem.innerText = total;
seatsElem.innerHTML = result.join("");
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>...</title>
</head>
<body>
<h2>Please choose a seat to book</h2>
<form action="/action_page.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="$100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="$65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="$55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="$50"> $50<br>
<p>Selected Seat(s)</p>
<!-- container for displaying selected seats -->
<ul id="selected-seats"></ul>
<div>
Total: $<span id="seats-total">0</span> USD
<input type="submit" value="Reserve Now">
</div>
</form>
</body>
</html>
Often, you'll want to generate the elements dynamically and add event listeners. Here's a toy example:
for (let i = 0; i < 1000; i++) {
const checkbox = document.createElement("input");
document.body.appendChild(checkbox);
checkbox.type = "checkbox";
checkbox.style.margin = 0;
checkbox.addEventListener("mouseover", e => {
e.target.checked = !e.target.checked;
});
checkbox.addEventListener("mouseout", e =>
setTimeout(() => {
e.target.checked = !e.target.checked;
}, 1000)
);
}
See also event delegation which lets you add a single listener on many child elements.

Here is a starter... About the math addition.
Since your question was tag with jQuery, It's a jQuery way.
Notice that the form will only send something like {vehicle:['on','','on','on']}... Which is way far from anyone would want to send to the server. But that is another question.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h2>Please choose a seat to book</h2>
<form action="/action_page.php" method="post">
<input type="checkbox" name="vehicle" id="A1" value="100">$100<br>
<input type="checkbox" name="vehicle" id="A2" value="65"> $65<br>
<input type="checkbox" name="vehicle" id="A3" value="55"> $55<br>
<input type="checkbox" name="vehicle" id="A4" value="50"> $50<br>
Selected Seat(s): <span id="seats"></span>
<br>
<br>
Total: $<span id="demo">0.00</span> USD <input type="submit" value="Reserve Now">
</form>
<script>
$(document).ready(function(){
var total=0;
var seats=[];
$("form input").on("click",function(){
var id=$(this).attr("id");
if($(this).is(":checked")){
total+=parseInt($(this).val());
seats.push(id);
}else{
total-=parseInt($(this).val());
seats.splice(seats.indexOf(id),1);
}
$("#demo").text(total.toFixed(2));
$("#seats").html(seats.sort().join(","));
});
});
</script>
</body>
</html>

Related

Need help on Checkbox onclick jquery

trying to learn jquery and made a simple checkbox with a function where you can make all the options read-only checking on "none of the above" button.
<html>
<body>
<form id="diagnosedForm">
<div>
<input type="checkbox" value="1"/>1
<br/>
<input type="checkbox" value="2"/>2
<br/>
<input type="checkbox" value="3"/>3
<br/>
</form><br/>
<input type="checkbox" value="" onclick="enableDisableAll(this);"/>None of the above
<script src="script.js">
</script>
</body>
</html>
function enableDisableAll(e) {
var own = e;
var form = document.getElementById("diagnosedForm");
var elements = form.elements;
for (var i = 0 ; i < elements.length ; i++) {
if(own !== elements[i] ){
if(own.checked == true){
elements[i].disabled = true;
elements[i].checked = false;
}else{
elements[i].disabled = false;
}
}
}
}
this will be the output
and the last checkbox will make it read-only
I want the same result but not putting onclick on the html file, instead using jquery to work it out.
You can assign an id to "none of the above" checkbox and then in your script.js you can do something like this:
// script.js
// Run enableDisableAll() on toggle click
$('#toggle').click(enableDisableAll)
function enableDisableAll() {
// Find all input elements inside "diagnosedForm"
const elements = $('#diagnosedForm input')
// Map thru inputs and toggle enable/disable state
elements.map((_, el) => {
$(el).prop('checked', false) // Reset checkboxes
$(el).prop('disabled', (i, v) => !v)
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<body>
<form id="diagnosedForm">
<div>
<input type="checkbox" value="1" />1
<br/>
<input type="checkbox" value="2" />2
<br/>
<input type="checkbox" value="3" />3
<br/>
</div>
</form>
<br/>
<input id="toggle" type="checkbox" value="" /> None of the above
</body>
</html>

Radio Button failed sometimes to get value

$("#btn").on("click",()=>{
const rdValue = $("#frm").serialize();
var _IsOccupant = false;
if ($("input[name='IsOccupant']:checked").val() == 1)
_IsOccupant = true;
alert(rdValue + " " + _IsOccupant);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<form id="frm">
<label>True</label>
<input type="radio" id="rbOwner" value="1" name="IsOccupant" required="" />
<label>False</label>
<input type="radio" id="rbOccupant" value="2" name="IsOccupant" required="" />
</form>
<button id="btn">Click Me</button>
I am wondering why sometime my code upon publish failed to determine the checkbox value(Checked checkbox). But when I manually debug it it returns the correct value. Does anyone knows the reason for this?.
Wrap your code inside
$(document).ready(function(){
// Your code goes here
$("#btn").on("click",()=>{
const rdValue = $("#frm").serialize();
var _IsOccupant = false;
if ($("input[name='IsOccupant']:checked").val() == 1)
_IsOccupant = true;
alert(rdValue + " " + _IsOccupant);
});
})
This will ensure your JavaScript executes only when the document is fully loaded.
To take the values from an input tag kind is necessary to use the .value function instead of .val
Is something similar to this:
<!DOCTYPE html>
<html>
<head>
<title>
Get value of selected
radio button
</title>
</head>
<body>
<p>
Select a radio button and click on Submit.
</p>
Gender:
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Others">Others
<br>
<button type="button" onclick="displayRadioValue()">
Submit
</button>
<br>
<div id="result"></div>
<script>
function displayRadioValue() {
var ele = document.getElementsByName('gender');
for(i = 0; i < ele.length; i++) {
if(ele[i].checked)
document.getElementById("result").innerHTML
= "Gender: "+ele[i].value;
}
}
</script>
</body>
</html>
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Female
<input type="radio" name="gender" value="Others">Others
<br>
<button type="button" onclick="displayRadioValue()">
Submit
</button>
<br>
<div id="result"></div>

jQuery - Sending "Select All" Check boxes with Multiple Forms

I have checked online for a solution to pass my values for the checkbox "select all". I have multiple forms in a page. So I will need to separate passing the values based on specific forms.
jQuery:
$(document).ready(function() {
$(".select-all").change(function () {
$(this).siblings().prop('checked', $(this).prop("checked"));
});
})
HTML for form:**
<div class="col">
<fieldset>
<form action="{$link->getLink('controller')|escape:'htmlall':'utf-8'}" method="post">
<p>
{foreach from=$payment item=row}
<input type="checkbox" name="payment[]" maxlength="50" value={$row.id_order}>
<label> ID: <b>{$row.id_order}</b></label><br/>
{/foreach}
<br/>
<input id="submit" name="submitpayment" type="submit" value="PACK ITEMS" class="button" />
</p>
</form>
</fieldset>
</div>
Error (Value is empty):
input type="checkbox" class="select-all" name="payment[]" value=""
SQL query to pass records:
public function displayOrdersbyID()
{
$query1 = new DbQuery();
$query1->select('o.id_order')
->from('orders','o')
->leftJoin('carrier','c','o.id_carrier=c.id_carrier')
->leftJoin('order_state_lang','s','o.current_state=s.id_order_state')
->where('c.name = ' . "'XXX'")
->where('s.name = ' . "'Payment accepted'");
$payment = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS($query1);
$this->context->smarty->assign( 'payment', $payment);
Controller:
if (Tools::isSubmit('submitpayment')) {
$ids= Tools::getValue('payment');
$query18 = new DbQuery();
$query18->select('id_order_state')
->from('order_state_lang')
->where('name = ' . "'Processing in progress'");
$updateinprogress = Db::getInstance()->getValue($query18);
foreach ($ids as $updateids) {
$objOrder = new Order($updateids);
$history = new OrderHistory();
$history->id_order = (int)$objOrder->id;
$history->id_employee = $cookie->id_employee;
$history->changeIdOrderState($updateinprogress, (int)($objOrder->id));
$history->add(true);
$history->save();
}
}
SELECT ALL checkbox:
<input type="checkbox" class="select-all" name="payment[]" value=
{$row.id_order}>
<label> SELECT ALL</label>
I was using the above code to create a SELECT ALL checkbox for the form, placing it outside the loop. I understand it is wrong and value is not passing, where should I place the checkbox at?
Any guidance is appreciated.
Thank you.
I think the problem in select-all value because there no initialization for $row.id_order in
<input type="checkbox" class="select-all" name="inprogress[]" value={$row.id_order}>
But if you assign the value of $row.id_order then might be not used in the following child like the {foreach from=$payment item=row} must use another variable identifier then row.
you working with a wrong practice you can't assign $row.order_id outside the loop.If there you want to use these element value in PHP then no need to do anything the $_POST['payment'] for the second form and $_POST['inprogress'] will return the value you want.
if no checkbox is selected then the result is returned blank.
and remember this will return an array type object.
The line
<input type="checkbox" class="select-all" name="inprogress[]" value={$row.id_order}>
lies outside the loop. Thus the value of {$row.id_order} will not be defined in your template. Check the DOM tree for compiled value.
And what is your final goal with the SELECT ALL button ? Is there any relation between the two forms?
Edit:
See the value of output variable. You can collect this value and pass it along with form submission.
<div class="col">
<fieldset>
<form>
<p>
<input type="checkbox" class="select-all" name="payment[]" value="22">
<label> SELECT ALL</label>
<br/><br/>
<input type="checkbox" name="payment[]" maxlength="50" value="a">
<label> ID: <b>A</b></label><br/>
<input type="checkbox" name="payment[]" maxlength="50" value="b">
<label> ID: <b>B</b></label><br/>
<input id="submit" name="submitinprogress" type="submit" value="PACK ITEMS" class="button" />
</p>
</form>
</fieldset>
</div>
$(document).ready(function() {
$(".select-all").change(function () {
$(this).siblings().prop('checked', $(this).prop("checked"));
let inputs = $(this).siblings("input[type=checkbox]");
let output = [];
for(let i = 0; i < inputs.length; i++){
output.push(inputs[i].value);
};
console.log(output); // ["a", "b"]
});
});

Javascript: How to get selected checkbox items in a table

I have a checkbox, where I am loading its inputs from a web service. I'm developing a function which filters the selected items and puts them in a table.
My checkbox looks like this:
<label class="checkbox" data-match-for="filtre-competences">
<input id="checkbox_competence" name="missionPlace" value="" type="checkbox" data-match-forcontent="id-competence">
<span class="check"></span>
<span class="checkbox-title" data-match-forcontent="titre-competence"></span>
<span>(<span data-match-forcontent="nb-mission"></span>)</span>
</label>
I want to filter the selected elements in a table and of course deselect items which may bed deselected dynamically.
My function looks like this:
selectCompetences:function () {
var checkbox = document.querySelector('#checkbox_competence');
var arr = new Array();
checkbox.addEventListener('click',function () {
if () {
//selected : add to table
arr.push(checkbox.getAttribute("value"))
}
else {
// deselected: remove from table
}
})
}
I need to complete this function. Any suggestions?
var values = new Array();
$.each($("input[name='case[]']:checked").closest("td").siblings("td"),
function () {
values.push($(this).text());
});
alert("val---" + values.join(", "));
function togglecheckboxes(master,group){
var cbarray = document.getElementsByName(group);
for(var i = 0; i < cbarray.length; i++){
cbarray[i].checked = master.checked;
}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="checkbox" id="cbgroup1_master" onchange="togglecheckboxes(this,'cbg1[]')"> Toggle All
<br><br>
<input type="checkbox" id="cb1_1" class="cbgroup1" name="cbg1[]" value="1"> Item 1<br>
<input type="checkbox" id="cb1_2" class="cbgroup1" name="cbg1[]" value="2"> Item 2<br>
<input type="checkbox" id="cb1_3" class="cbgroup1" name="cbg1[]" value="3"> Item 3<br>
<input type="checkbox" id="cb1_4" class="cbgroup1" name="cbg1[]" value="4"> Item 4<br>
</body>
</html>

Display value of checkbox in textarea

I have here a code that will display the value of the checkbox when checked. My problem is I don't know how I will add up all the numbers, that when I checked a checkbox the number or value will display automatically to the text area and when I checked another checkbox it will add up to the first checkbox that I checked and when I checked another checkbox it should also add up from the first two checkbox. How will I do that?
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript">
function add_sub(el)
{
if (el.checked)
{
var total = el;
total.form.elements['type'].value+=el.value;
}
else
{
var re=new RegExp('(.*)'+el.value+'(.*)$');
el.form.elements['type'].value=el.form.elements['type'].value.replace(re,'$1$2');
}
}
</script>
</head>
<body>
<form name="form1" method=post>
<textarea name="type" rows="5" cols="35" onclick="this.focus();this.select();"></textarea><br>
<input type="checkbox" name="mis1" id="id1" value="1" onclick="add_sub(this);"><label>1</label><br>
<input type="checkbox" name="mis2" id="id2" value="2" onclick="add_sub(this);"><label>2</label><br>
<input type="checkbox" name="mis6" id="id3" value="3" onclick="add_sub(this);"><label>3</label><br>
<input type="checkbox" name="mis6" id="id4" value="4" onclick="add_sub(this);"><label>4</label>
</form>
</body>
Please check this fiddle if this is what you meant:
http://jsfiddle.net/zyfmt4at/5/
this is the script:
var currNum = 0;
var txtArea = document.getElementById("txtArea");
var form = document.getElementById("mainForm");
function add_sub(el){
debugger;
if (el.checked)
{
currNum += parseInt(el.value,10);
}
else
{
currNum -= parseInt(el.value,10);
}
txtArea.value = currNum;
}
form.addEventListener("click", function(ev){
if(ev.target.getAttribute("type") == "checkbox"){
add_sub(ev.target);
}
},false);
this is the HTML:
<body>
<form id="mainForm" name="form1" method=post>
<textarea id="txtArea" name="type" rows="5" cols="35" onclick="this.focus();"></textarea><br>
<input type="checkbox" name="mis1" id="id1" value="1"><label>1</label><br>
<input type="checkbox" name="mis2" id="id2" value="2"><label>2</label><br>
<input type="checkbox" name="mis6" id="id3" value="3"><label>3</label><br>
<input type="checkbox" name="mis6" id="id4" value="4"><label>4</label>
</form>
</body>
The solutions proposed above are based on an assumption that the checkbox values are numbers, in case you are in need of string values. You may suggest this.
function add_sub(el)
{
var cbs = document.getElementById('checkboxes').getElementsByTagName('input');
var textareaValue = '';
for (var i = 0, len = cbs.length; i<len; i++) {
if ( cbs[i].type === 'checkbox' && cbs[i].checked) {
textareaValue += cbs[i].value + ' ';
}
}
document.getElementById('textarea').value = textareaValue;
}
and
<textarea id="textarea" name="type" rows="5" cols="35" onclick="this.focus();this.select();"></textarea><br>
<div id="checkboxes">
<input type="checkbox" name="mis1" id="id1" value="1" onclick="add_sub(this);"><label>1</label><br>
<input type="checkbox" name="mis2" id="id2" value="2" onclick="add_sub(this);"><label>2</label><br>
<input type="checkbox" name="mis6" id="id3" value="3" onclick="add_sub(this);"><label>3</label><br>
<input type="checkbox" name="mis6" id="id4" value="4" onclick="add_sub(this);"><label>4</label>
</div>
And the working plunker:
http://plnkr.co/edit/HWHRsBn7s7vJ9KI4UauU
Some tips:
Don't listen to click events to detect changes in checboxes. They can change in other ways, e.g. with the keyboard. You can listen to change events instead.
Don't use event handler content attributes in the HTML source. Add event listeners using JS.
Don't add the same event listener to all events. Delegate it to a common ancestor instead.
br elements are ugly. Better use display: block.
var sum = 0,
form = document.forms.form1,
text = form1.elements.type;
text.addEventListener('focus', text.select.bind(text));
form.addEventListener('change', function(e) {
if(e.target.type == 'checkbox') {
sum += e.target.value * (e.target.checked ? 1 : -1);
text.value = sum;
}
});
label { display: block; }
<form name="form1" method="post">
<textarea name="type" rows="5" cols="35">0</textarea>
<label><input type="checkbox" name="mis1" id="id1" value="1">1</label>
<label><input type="checkbox" name="mis2" id="id2" value="2">2</label>
<label><input type="checkbox" name="mis6" id="id3" value="3">3</label>
<label><input type="checkbox" name="mis6" id="id4" value="4">4</label>
</form>

Categories

Resources