How to check uncheck checkbox all at the same time - javascript

All I want is to check / uncheck all of the choices with one check button.
<form action="process.php" method="post">
<p> Select pet: </p>
<p> <input type="checkbox" name="dog" value="dog"> Dog </p>
<p> <input type="checkbox" name="cat" value="cat"> Cat </p>
<p> <input type="checkbox" name="bird" value="Tbird"> Bird </p>
<p> <input type="checkbox" name="checkall" value="checkall"> All </p>
what code / codes am I missing? I need "All" to uncheck / check all choices if it is chosen by the user. I use xampp for this one.

You can do something like this (jQuery):
$("#checkall").change(function () {
$("input:checkbox").prop('checked', $(this).prop("checked"));
});
Just add the id attribute to the checkbox:
<input type="checkbox" id="checkall" name="checkall" value="checkall">

Create a class for you checkboxes and use Javascript:
<form .....>
<input type="checkbox" class="myCheckboxes" name="dog" value="dog" />
<!--rest of the checkboxes with the same class name but different names and values follow-->
<button type="button" class="checkedAll">Check All</button>
</form>
<script type="text/javascript">
(function() {
var checked = false;
$('button.checkedAll').click(function() {
checked = !checked;
$('.myCheckboxes').prop('checked', checked);
if (checked) $(this).text('Uncheck All');
else $(this).text('Check All);
});
})();
</script>

If you add an id attribute with the value "petForm" to your form element.
<form id="petForm" action="process.php" method="post">
You can use the following pure Javascript.
<script>
document.addEventListener("DOMContentLoaded", function(event) {
var form = document.getElementById("petForm");
if (form) {
var checkAll = form.querySelector("input[type='checkbox'][name='checkall']");
var checkBoxes = form.querySelectorAll("input[type='checkbox']:not([name='checkall'])");
checkAll.addEventListener("change", function(e) {
for (checkBox of checkBoxes) {
checkBox.checked = this.checked;
}
});
}
}
</script>
It adds an event listener to the document that waits for the DOM to be loaded, then identifies the form by the added id attribute. If it finds the form, then it stores the "checkall" input element and all the other input elements of type checkbox in the form in two different variables. After that it adds an on change event listener to the "checkall" checkbox input element that sets all other checkbox input elements in the form to the same value as the checkall checkbox input element.
Here's a JSFiddle of the code above running.
If your form contains additional checkboxes that you don't want checked by the checkall checkbox, you'll need to modify the way checkBoxes is populated. Similarly if you have multiple collections of checkboxes then you'll need to find a way to differentiate between them.

Related

Issue with script being triggered by wrong checkbox

I'm trying to enable/disable a place order button based on whether or not the terms acceptance checkbox has been checked. The script I have been working on works fine for that, but it's also triggered when a different checkbox (with a different id) is checked. Although the other checkbox enables the button, it doesn't disable it again when un-checking it. So I think it's something wrong with the 'on change' part.
I've tried everything I could find and can't make it work only when the checkbox with id 'terms' is checked:
<script>
jQuery(window).on('load',function(){
setTimeout(function(){
jQuery('#payment #place_order').attr("disabled","disabled");
},1000);
});
jQuery(document).on('change','#terms',function() {
var ischecked = document.getElementById("terms");
if(ischecked.checked == false){
jQuery('#payment #place_order').attr("disabled","disabled");
}else{
jQuery('#payment #place_order').removeAttr("disabled");
}
});
</script>
The terms checkbox is as below:
<input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox ios-switch" name="terms" id="terms">
And the other one that triggers it is as below:
<input class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" id="createaccount" type="checkbox" name="createaccount" value="1">
Your code is not clear.
Assuming the place order has the id of #place_order, there is no need to add the container
jQuery(function() { // on page load
jQuery('#place_order').attr("disabled", "disabled");
jQuery(document).on("change", "#terms", function() { // assuming the terms is dynamically inserted
if (!this.checked) {
jQuery('#place_order').attr("disabled", "disabled");
} else {
jQuery('#place_order').removeAttr("disabled");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Terms <input type="checkbox" class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox ios-switch" name="terms" id="terms"><br/>
<button id="place_order">Place order</button>
<hr/>
Create account <input class="woocommerce-form__input woocommerce-form__input-checkbox input-checkbox" id="createaccount" type="checkbox" name="createaccount" value="1">

Enable or disable target element based on checkbox checked state

i'm basically JavaScript newbie and I'm trying to resolve this problem of mine for quite a while. So,i'm doing JS school project and I need to make connection between checkbox and text form. If checkbox is not checked, text form should be disabled and vice versa. This is piece of code I have written:
function cbtf() {
if (document.getElementById('checkbox').checked==false) {
document.getElementById('textform').disabled=true;
}
}
Can anyone write a new code ? That would be much of a help.
Simply attach a method to checkbox's onclick handler:
function enableElement(id, enable) {
document.getElementById(id).disabled=!enable;
}
<label>
<input
type="checkbox"
onclick="enableElement('textform', this.checked)"
/>
ENABLE
</label>
<br/>
<textarea id="textform" style="width:100%; height:200px" disabled>
THIS IS TEXTAREA WITH ID "textform"
</textarea>
or another simplification without creating special one-liner method - just define Your will directy in onclick event:
<label>
<input
type="checkbox"
onclick="document.getElementById('textform').disabled = !this.checked"
/>
ENABLE
</label>
<br/>
<textarea id="textform" style="width:100%; height:200px" disabled>
THIS IS TEXTAREA WITH ID "textform"
</textarea>
You can add a click event to the checkbox, and assign it's check state to the disabled property of the TextBox.
document.querySelector('input[type=checkbox]').onclick = function(e) {
document.querySelector('input[type=text]').disabled = e.target.checked;
};
<input type="checkbox" name="">
<input type="text" name="">
You won't get that to work unless you attach an event to the checkbox, so I would suggest something like this:
var textbox = document.getElementById('textform');
var checkbox = document.getElementById('checkbox');
checkbox.addEventListener("change", function() {
if (checkbox.checked) {
textbox.disabled = false;
} else {
textbox.disabled = true;
}
})

Add required to input of hidden div when radio is checked

What I'm trying to do is to set hidden div with inputs depended on checked radio input.
This is the logic:
If the first radio is checked the first div is shown, there I want to add hidden inputs with some values...
If the second radio is checked I want the input to be added with required..
And, it shouldn't be required if the 2nd radio isn't checked...
I've tried a few things over some time and got some effects but can't get it work as I want, Here is the code that i'm currently trying to work with, sorry but it's messed up and fails...
So Any help will be much appreciated...
/*
// this code is working but I messed the HTML while trying to get it work with the other code below...
$(document).ready(function() {
$("div.hiddendiv").hide();
check();
$("input[name$='name02']").change(check);
function check() {
var test = $("input[name$='name02']:checked").val();
$("div.hiddendiv").hide();
$("#" + test).show();
}
}
*/
// The code i'm trying to work with...
$(function() {
var radio = $("#closed");
var hidden = $("#hide");
hidden.hide();
checkbox.change(function() {
if (checkbox.is(':checked')) {
hidden.show();
//add required
$('#name02').prop('required', true);
} else {
hidden.hide();
//clear when hidden checked
$("#name02").val("");
//remove required
$('#name02').prop('required', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="closed" value="01"> Closed
<input type="radio" id="open" value="02"> Open
<div name="01" class="hiddendiv">
<input name="name01" type="hidden" value="code">
</div>
<div name="02" id="hide" class="hiddendiv">
<input name="name02" type="text" value="">
</div>
Here is the JSFiddle,
try this code
give same name of radio button so it will work as a group and
also set id of input tag as name02 so its use as a #name02 in jquery
so it will work
$(function() {
var radio = $("#closed");
var hidden = $("#hide");
hidden.hide();
$(this).click(function() {
if ($('#closed').is(':checked')) {
hidden.show();
$('#name02').prop('required', true);
} else {
hidden.hide();
//clear when hidden checked
$("#name02").val("");
//remove required
$('#name02').prop('required', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name='btn' id="closed" value="01"> Closed
<input type="radio" name='btn' id="open" value="02"> Open
<div name="01" class="hiddendiv">
<input name="name01" type="hidden" value="code">
</div>
<div name="02" id="hide" class="hiddendiv">
<input name="name02" id="name02" type="text" value="">
</div>
Part of your problem is that you need to set the name attribute of your radio buttons to be the same value, otherwise the HTML won't know that they belong to the same group.
I've updated the JSfiddle here
https://jsfiddle.net/hba4d83k/2/
What i have done is add a change event handler to your the radio group and then did some conditional logic to show/hide the relevant inputs.

Find a selector and update

I have a three different radio buttons and based on the selection of the radio button I would like to capture which radio button the user clicked and store that in a hidden input textbox for later use.
Here is the code I have tried, which doesn't seem to be working:
//clicked on first radioButton:
$('#Employee').change(function () {
if (this.checked) {
$('#multi').show();
$('#Type').attr("EmployeeSelected");
}
});
//clicked on second radioButton:
$('#Employer').change(function () {
if (this.checked) {
$('#multi').show();
$('#Type').attr("EmployerSelected");
}
});
My page looks like this:
<fieldset id="multi" class="fieldset-auto-width">
<legend>
Selected Form
</legend>
<form action="/PostToDb" method="post">
<input type="text" name="Type" value="xx" />
<div>
......................
</div>
</form>
How do I update the textbox to whichever radio button is selected?
$("input:radio[name=emp]").change(function () {
if ($(this).val()==0) {
$("input:text").val('first radio');
}else if ($(this).val()==1) {
$("input:text").val('second radio');
}else if ($(this).val()==2) {
$("input:text").val('third radio');
}
});
FIDDLE
$('#Employer')--> when using # you will be selecting id as for . it is for class and so on.
$('#Type').attr("EmployerSelected"); to assign a text to input use val() as $('#Type').val("EmployerSelected"); meaning the element with id Type will have the value EmployerSelected
Try replacing .attr() with .val() and use the correct selector as follows:
$('[name="Type"]').val("EmployerSelected");
Try add id attribute to the input box,as
<input id="Type" type="text" name="Type" value="xx" />
hope helpful.

JavaScript: How to detect if an HTML checkbox was selected?

How do I:
detect if an HTML checkbox has be clicked/selected?
retrieve which checkbox(es) have been selected?
Example code:
<FORM ACTION="...">
<INPUT TYPE=CHECKBOX VALUE="1">1 bedroom<BR>
<INPUT TYPE=CHECKBOX VALUE="2">2 bedrooms<BR>
<INPUT TYPE=CHECKBOX VALUE="3">3 bedrooms<BR>
<INPUT TYPE=CHECKBOX VALUE="4+">4+ bedrooms<P>
</FORM>
Meaning,
if the web user selects "1 bedroom", I want an event to fire to inform me the user selected "1 bedroom".
As you can see, a user can select multiple checkboxes. For example, they might want to see homes that have either "1 bedroom" or "2 bedrooms". So they would selected both checkboxes. How do I retrieve the checkbox values when multiple checkboxes have been selected?
In case it helps, I would be open to using JQuery to simplify this.
jQuery to the rescue! (since you tagged it as such):
$('input:checkbox[name=bedrooms]').click(function() {
var values = $('input:checkbox[name=bedrooms]:checked').map(function() {
return this.value
}).get();
// do something with values array
})
(make sure to add a name="bedrooms" attribute in the html for your checkboxes; you'll need them when submitting the form anyway, in order to retrieve them on the server).
I've used a few pseudo-selectors:
"input:checkbox" finds all the input checkboxes on the page
"[name=bedrooms]" finds all the elements with attribute name="bedrooms"
":checked" finds all the elements with attribute checked=true
Combine them as "input:checkbox[name=bedrooms]:checked" and jQuery gives you all the checked checkboxes.
For each one I pluck out their value attribute into an array you can simply iterate over and do what you wish.
Edit
You can optimize this code to save a reference to your checkboxes instead of telling jQuery to go fetch them all everytime there's a click:
var $checkboxes = $('input:checkbox[name=bedrooms]');
$checkboxes.click(function() {
var values = $checkboxes
.filter(function() { return this.checked })
.map(function() { return this.value })
.get();
// do something with values array
})
In this sample I've saved the checkboxes into var $checkboxes. On click of any checkbox, instead of going back to the DOM to grab the checked ones, we simply filter $checkboxes down to only the checkboxes that are checked, and for each one pluck out the value attribute into an array. The get() is just an obscure requirement to convert the "jQueryized" array to a regular JavaScript Array.
1) Use the onclick attribute.
2) You could give them each the same name and use $('input[name=yourname]:checked') to get them all.
[Edit] as requested, here's an SSCCE.
<!doctype html>
<html>
<head>
<script src="jquery.js"></script>
<script>
$(document).ready(init);
function init() {
// Add onclick function to every checkbox with name "bedrooms".
$('input[name=bedrooms]').click(showCheckedValues);
}
function showCheckedValues() {
// Gather all values of checked checkboxes with name "bedrooms".
var checked = $('input[name=bedrooms]:checked').map(function() {
return this.value;
}).get();
alert(checked);
}
</script>
</head>
<body>
<form>
<input type="checkbox" name="bedrooms" value="1">1 bedroom<br>
<input type="checkbox" name="bedrooms" value="2">2 bedroom<br>
<input type="checkbox" name="bedrooms" value="3">3 bedroom<br>
<input type="checkbox" name="bedrooms" value="4+">4+ bedroom<br>
</form>
</body>
</html>
<form name="myForm">
<input type="checkbox" name="myCheck"
value="My Check Box"> Check Me
</form>
Am I Checked?
This is from a textbook called JavaScript in 10 Easy Steps or Less by Arman Danesh - so i'd assume this works. hope it helps
Assign names and/or IDs to your checkbox elements so that you can distinguish them in code. Then, using jQuery, add events with bind if you want to handle the check/uncheck state changes.
Use IDs on your checkbox.
<FORM ACTION="...">
<INPUT TYPE=CHECKBOX id="c1" VALUE="1">1 bedroom<BR>
<INPUT TYPE=CHECKBOX id="c2" VALUE="2">2 bedrooms<BR>
<INPUT TYPE=CHECKBOX id="c3" VALUE="3">3 bedrooms<BR>
<INPUT TYPE=CHECKBOX id="c4" VALUE="4+">4+ bedrooms<P>
</FORM>
$('c1').checked // returns whether the 1 bedroom checkbox is true or false
You can use the .checked property on a checkbox to retrieve whether a checkbox has been checked. To fire an event when a checkbox is checked, you can use the click event in jquery. Something like the below would work to list all checkboxes on the page that have been checked.
$("input[type='checkbox']").click(function() {
// if you want information about the specific checkbox that was clicked
alert("checkbox name : " + $(this).name + " | checked : " + $(this).checked);
// if you want to do something with ALL the checkboxes on click.
$.each($["input[type='checkbox']", function(i, checkEl) {
// put any of your code to do something with the checkboxes here.
alert("checkbox name : " + checkEl.name + " | checked : " + checkEl.checked);
});
});
You can use events to see if a checkbox was selected (onChange). You can read more about it at the Essential Javascript tutorial (see the section entitled: Javascript is an Event Driven Language)
Markup:
...<input type="checkbox">...
detect if an HTML checkbox has be clicked/selected?
a: using jQuery 1.7+:
$(function(){
$("input").click(function () {
console.log($(this)[0].checked);
});
});
retrieve which checkbox(es) have been selected?
a: again using jQuery 1.7+:
console.log($('input:checked'));
Hope this helps.
If you do not want to use JQuery you could always use
document.GetElementById("cbxCheckbox1");

Categories