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");
Related
I need assistance in storing checkbox API values.
I have multiple checkboxes and I can display API values in html when checkbox is checked.
But how do I store the initial value of a checked checkbox and show it in a span?
I currently get “on” value instead of API initial value.
eg. The value I want is “Faculty Lecture” as stored in the API
Below is my code:
//store checkbox values
$('#myCheck1').on('change', function() {
$('.results').html(this.checked ? this.value : '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="myCheck1" name="checks" class="round">
<span id="eventTitle" class="results"></span>https://stackoverflow.com/questions/ask#
Use the checkbox value attribute to store the value of the checkbox, e.g.
<input type="checkbox" id="myCheck1" name="checks" class="round" value="Faculty Lecture">
That way this.value returns "Faculty Lecture"
Also, use the class in your selector instead of the id of the element by changing:
$('#myCheck1').on('change', function() { ....
To:
$('.round').on('change', function() { .....
Since you want to get value attached to checkbox.
You should use <label> instead of <span> with input checkbox to show its value initially.
Example
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="myCheck1" name="checks" class="round">
<label for="myCheck1">Faculty Lecture</label>
You can get label of checkbox in jquery like
$("label[for='myCheck1']")
To get label text you can use following:
$("label[for='myCheck1']").text()
Following should be your html and jquery
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="myCheck1" name="checks" class="round">
<label for="myCheck1">Faculty Lecture</label>
<span class='results'></span>
<script>
//store checkbox values
$('#myCheck1').on('change', function() {
var lb=$("label[for='myCheck1']").text();
$('.results').html(lb);
});
</script>
I have a checkbox with the same name and id but different value.
I trying to get the value when I click on the checkbox in order to pass it to a ajax request. What ever I try I get the same result it only returns the first value in the list (it is actually in a php loop)
function checkCheckboxState() {
if ($('.displayme').is(':checked')) {
//tried all of these...
//var id = $('.displayme').first().attr( "value" );
//var id = $('.displayme').val();
//var id = $(this).val();
alert(id);
}
var id = $(":checkbox[name='displayme']:checked").val();
}
<input type="checkbox" name="displayme" value="27" id="displayme" class="displayme" onclick="checkCheckboxState()">
<input type="checkbox" name="displayme" value="28" id="displayme" class="displayme" onclick="checkCheckboxState()">
<input type="checkbox" name="displayme" value="29" id="displayme" class="displayme" onclick="checkCheckboxState()">
You shouldn't have the same id used several times on the same page.
You can bind an event on the change of the checkbox and then get the value with this :
$("checkbox.displayme").on("change",function(){
var checker = $(this).is(':checked');
//your ajax code here
});
And if your checkbox are generated on a php loop, you can use the index of the loop to generate different id (but with the code above you don't need any id).
Your first problem is that you have multiple elements with the same id. They need to be unique. In this case you could even remove them as you have the common class names to identify the elements.
To solve your actual problem you need to get a reference to the clicked checkbox within the event handler. As you're already using jQuery, you could do that using the change event handler. Try this:
$(function() {
$('.displayme').change(function() {
if (this.checked)
console.log(this.value);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="displayme" value="27" class="displayme">
<input type="checkbox" name="displayme" value="28" class="displayme">
<input type="checkbox" name="displayme" value="29" class="displayme">
Alternatively you can use map() to build an array of all the selected checkboxes which can then be passed in a single AJAX request:
$(function() {
$('.displayme').change(function() {
var values = $('.displayme:checked').map(function() {
return this.value;
}).get()
console.log(values);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="displayme" value="27" class="displayme">
<input type="checkbox" name="displayme" value="28" class="displayme">
<input type="checkbox" name="displayme" value="29" class="displayme">
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.
i have an array of checkbox (to use with php), bu i want to use ajax to make somethings with this values from checkbox, i want to get the value from each checkbox and make an ajax request.
I have this:
$("#checked").each(function(i, val){
var k = $(i).value();
console.log(k);
});
but no success.
html:
<input id="checado" type="checkbox" name="ids[]" value="78">
<input id="checado" type="checkbox" name="ids[]" value="79">
<input id="checado" type="checkbox" name="ids[]" value="80">
<input id="checado" type="checkbox" name="ids[]" value="81">
With a small change to your HTML you can use the following JavaScript (demo):
<input class="checado" type="checkbox" name="ids[]" value="78"> 78<br/>
<input class="checado" type="checkbox" name="ids[]" value="79"> 79<br/>
<input class="checado" type="checkbox" name="ids[]" value="80"> 80<br/>
<input class="checado" type="checkbox" name="ids[]" value="81"> 81<br/>
<button id='Submit'>Submit</button>
<script>
$('#Submit').on('click', function() {
var values = []
$('.checado:checked').each(function () {
var e = $(this);
values.push(e.val());
});
alert(values);
});
</script>
For a more detailed breakdown of what is going on, the check boxes have a checked state and a value. the jQuery Selector $('.checado:checked') will return just the checked check boxes (You should use class when you have multiple elements and id only when you are identifying a single element, browsers and CSS can appear lazy about this but incorrect usage will yield unpredictable results). The other change is to grab the values by the jQuery method .val() which helps hide the input type and browser specific ways values are fetched.
You're using jQuery, which uses it's own .val() method. Replace .value() with .val().
I have a checkbok as selectAll
Select All
<input class="all-select" type="checkbox" value="" name="">
i also have a list of friends with a checkbox each which is populated dynamically.
<ul>
<li><span><img src="img.src" ></span><strong>Name</strong>
<br />Email
<input name="" type="checkbox" value="" class="chk-box">
</li>.....</ul>
when i click the select all checkbox, then all the checkboxes of my list should get selected, the javascript code for which is given below :
$("#slide_top_pop").on("click", ".all-select", function (event) {
if ($(this).is(':checked')) {
$('input.chk-box').attr('checked', true);
} else {
$('input.chk-box').attr('checked', false);
}
});
Now the problem is this that when i first time select the Select All check box then the list get selected but when i unchecked it and check again then the list is not selected and when i tried to verify it on Mozilla what is the checked property(attribute) for the list then i get this :
<input class="chk-box" type="checkbox" value="" name="" checked="checked">
which says that the checkbox is selected but i cant see the selected tick in the list.
I dont understand what the problem is .
any solution is appreciated thanks.
Use .prop() instead of .attr() like:
$("#slide_top_pop").on("click", ".all-select", function (e) {
$('input.chk-box').prop('checked', this.checked);
});