Checkbox value is always 'on' [duplicate] - javascript

This question already has answers here:
How do I check whether a checkbox is checked in jQuery?
(68 answers)
Closed 9 years ago.
this is my checkbox
HTML
<label class="checkbox">
<input id="eu_want_team" name="eu_want_team" type="checkbox">
</label>
JQuery
var eu_want_team = $('#eu_want_team').val();
alert(eu_want_team);
Its always displaying ON, is it checked or not. Whats the problem with it?

Use .is(':checked') instead: Working jsFiddle
var eu_want_team = $('#eu_want_team').is(':checked');
alert(eu_want_team);
or as #Itay said in comments you can use jQuery's .prop() to get the checked property value:
alert($("#eu_want_team").prop("checked"));

<label class="checkbox">
<input id="eu_want_team" name="eu_want_team" type="checkbox" value="somevalue">
</label>
<script>
var ele = document.getElementById("eu_want_team");
if(ele.checked)
alert(ele.value)
</script>

This will work :
if ($('#element').is(":checked")) {
eu_want_team = 1;
} else {
eu_want_team = 0;
}
alert(eu_want_team);

Have a quick look at this answer for checking if a checkbox is checked.
How to check whether a checkbox is checked in jQuery?
But basically you want to do something like below to check its value:
if ($("#element").is(":checked")) {
alert("I'm checked");
}

i think this is what you want to do
$("#eu_want_team").click(function(){
alert($(this).is(':checked'));
}

Try this
if ( $('#element').is(':checked')){
alert(element);
}

Related

What is the opposite of :checked [duplicate]

I have a list of checkboxes:
<input type="checkbox" name="answer" id="id_1' value="1" />
<input type="checkbox" name="answer" id="id_2' value="2" />
...
<input type="checkbox" name="answer" id="id_n' value="n" />
I can collect all the values of checked checkboxes; my question is how can get all the values of unchecked checkboxes? I tried:
$("input:unchecked").val();
to get an unchecked checkbox's value, but I got:
Syntax error, unrecognized expression: unchecked.
Can anybody shed a light on this issue?
Thank you!
As the error message states, jQuery does not include a :unchecked selector.
Instead, you need to invert the :checked selector:
$("input:checkbox:not(:checked)")
$("input:checkbox:not(:checked)") Will get you the unchecked boxes.
Also it can be achieved with pure js in such a way:
var matches = document.querySelectorAll('input[type="checkbox"]:not(:checked)');
You can do so by extending jQuerys functionality. This will shorten the amount of text you have to write for the selector.
$.extend($.expr[':'], {
unchecked: function (obj) {
return ((obj.type == 'checkbox' || obj.type == 'radio') && !$(obj).is(':checked'));
}
}
);
You can then use $("input:unchecked") to get all checkboxes and radio buttons that are checked.
$("input[type='checkbox']:not(:checked):not('\#chkAll\')").map(function () {
var a = "";
if (this.name != "chkAll") {
a = this.name + "|off";
}
return a;
}).get().join();
This will retrieve all unchecked checkboxes and exclude the "chkAll" checkbox that I use to check|uncheck all checkboxes. Since I want to know what value I'm passing to the database I set these to off, since the checkboxes give me a value of on.
//looking for unchecked checkboxes, but don’t include the checkbox all that checks or unchecks all checkboxes
//.map - Pass each element in the current matched set through a function, producing a new jQuery object containing the return values.
//.get - Retrieve the DOM elements matched by the jQuery object.
//.join - (javascript) joins the elements of an array into a string, and returns the string.The elements will be separated by a specified separator. The default separator is comma (,).
You can use like this :
$(":checkbox:not(:checked)")
To select by class, you can do this:
$("input.className:checkbox:not(:checked)")
$(".clscss-row").each(function () {
if ($(this).find(".po-checkbox").not(":checked")) {
// enter your code here
} });

Check one checkbox when other is selected [duplicate]

I want the checkbox with the value 2 to automatically get checked if the checkbox with the value 1 is checked. Both have the same id so I can't use getElementById.
html:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name">2
I tired:
var chk1 = $("input[type="checkbox"][value="1"]");
var chk2 = $("input[type="checkbox"][value="2"]");
if (chk1:checked)
chk2.checked = true;
You need to change your HTML and jQuery to this:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.on('change', function(){
chk2.prop('checked',this.checked);
});
id is unique, you should use class instead.
Your selector for chk1 and chk2 is wrong, concatenate it properly using ' like above.
Use change() function to detect when first checkbox checked or unchecked then change the checked state for second checkbox using prop().
Fiddle Demo
Id should be unique, so that set different ids to your elements, By the way you have to use .change() event to achieve what you want.
Try,
HTML:
<input type="checkbox" value="1" id="user_name1">1<br>
<input type="checkbox" value="2" id="user_name2">2
JS:
var chk1 = $("input[type='checkbox'][value='1']");
var chk2 = $("input[type='checkbox'][value='2']");
chk1.change(function(){
chk2.prop('checked',this.checked);
});
You need to change the ID of one. It is not allowed by W3C standard (hence classes vs ID's). jQuery will only process the first ID, but most major browsers will treat ID's similar to classes since they know developers mess up.
Solution:
<input type="checkbox" value="1" id="user_name">1<br>
<input type="checkbox" value="2" id="user_name_2">2
With this JS:
var chk1 = $('#user_name');
var chk2 = $('#user_name2');
//check the other box
chk1.on('click', function(){
if( chk1.is(':checked') ) {
chk2.attr('checked', true);
} else {
chk2.attr('checked', false);
}
});
For more information on why it's bad to use ID's see this: Why is it a bad thing to have multiple HTML elements with the same id attribute?
The error is probably coming here "input[type="checkbox"]
Here your checkbox is out of the quotes, so you query is looking for input[type=][value=1]
Change it to "input[type='checkbox'] (Use single quote inside double quote, though you don't need to quote checkbox)
http://api.jquery.com/checked-selector/
first create an input type checkbox:
<input type='checkbox' id='select_all'/>
$('#select_all').click(function(event) {
if(this.checked) {
$(':checkbox').each(function() {
this.checked = true;
});
}
});

How to receive values from 'HTML form' to a javascript code? [duplicate]

This question already has answers here:
How can we access the value of a radio button using the DOM?
(12 answers)
Closed 9 years ago.
The form includes Radio, Select, Input etc..
var variable = document.getElementById('anyId').value;
It works fine with input element, but with radio button element it's not working as desired!
On my HTML page (for radio) the code looks something like this,
<input type="radio" id="radioValue" name="radio" value="2">Radio_1
<input type="radio" id="radioValue" name="radio" value="1">Radio_2
and in the script
var radio_value = document.getElementById('radioValue').value;
radio_value is always equal to 2, it doesn't matter whether you select radio_1 or radio_2.
By using getElementsByName
var selectedradio;
var radios = document.getElementsByName("radio");
for(var i = 0; i < radios.length; i++) {
if(radios[i].checked == true) {
alert(radios[i].value);
selectedradio = radios[i].value;
}
}
ID's must be unique. So you should change your code to this:
<input type="radio" id="radioValue1" name="radio" value="2">Radio_1
<input type="radio" id="radioValue2" name="radio" value="1">Radio_2
And then you can get those values by:
var radio_value1 = document.getElementById('radioValue1').value;
var radio_value2 = document.getElementById('radioValue2').value;
//or
var radio_value=document.querySelector('input[name="radio"]:checked').value;
// in this last case you don't need even to have id's in the buttons
Otherwise trying to read two values with the same ID will give you just the first one of them.
Pure javascript for most modern browsers.(works also in ie 9)
if you have just one form and only one group of radio's use querySelector
it's the new proper way.
var radio_value=document.querySelector('input[type="radio"]:checked').value
You can also easely extend it if you have multiple radio groups and forms.
var radio_value=document.querySelector('#YOURFORM input[name="radio"]:checked').value

Check if at least one checkbox is checked using jQuery

I have five checkboxes. Using jQuery, how do I check if at least one of them is checked?
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
<br />
<input type="checkbox" name="service[]">
is() can do this, and is arguably the only acceptable use of is(":checked"):
From the jQuery docs, http://api.jquery.com/is/:
Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
alert($("input[name='service[]']").is(":checked"));
Example: http://jsfiddle.net/AndyE/bytVX/1/ (based on the fiddle by Brandon Gano)
Alternatively, and potentially faster, you can pass a function to is():
$("input[name='service[]']").is(function () {
return this.checked;
});
This should do the trick:
function isOneChecked() {
return ($('[name="service[]"]:checked').length > 0);
}
Edit: The original solution in this answer is inefficient and should not be used. Please see the revised solution based on comments and examples from other answers to this question.
The original (bad) solution follows:
// DO NOT USE; SEE BELOW
$('button').click(function () {
var atLeastOneIsChecked = false;
$('input:checkbox').each(function () {
if ($(this).is(':checked')) {
atLeastOneIsChecked = true;
// Stop .each from processing any more items
return false;
}
});
// Do something with atLeastOneIsChecked
});
The use of .each() is redundant in this example, as .is() can be used directly on the set of objects rather than manually iterating through each one. A more efficient solution follows:
$('button').click(function () {
var atLeastOneIsChecked = $('input:checkbox').is(':checked');
// Do something with atLeastOneIsChecked
});
Note that one of the comments indicates a strong dislike for $(this).is(':checked'). To clarify, there is nothing wrong with is(':checked') in cases where you are testing a set of objects. That said, calling is(':checked') on a single item is much less efficient than calling .checked on the same item. It also involves an unnecessary call to the $ function.
Another answer:
!!$("[type=checkbox]:checked").length
or
!!$("[name=service[]]:checked").length
It depends on what you want.
var checkboxes = document.getElementsByName("service[]");
if ([].some.call(checkboxes, function () { return this.checked; })) {
// code
}
What you want is simple, get all the elements with the name, then run some code if some of those elements are checked.
No need for jQuery.
You may need an ES5 shim for legacy browsers though
You should try like this....
var checkboxes = $("input[type='checkbox']"),
submitButt = $("input[type='submit']");
checkboxes.click(function() {
submitButt.attr("disabled", !checkboxes.is(":checked"));
});
you need to check if checkbox is checked or not.
$("#select_all").click(function(){
var checkboxes = $("input[type='checkbox']");
if(checkboxes.is(":checked"))
alert("checked");
else
alert("select at least one;
});
var atLeastOneIsChecked = $('input[name="service[]"]:checked').length > 0;
The square bracket [] is not necessary:
var atLeastOneIsChecked = $("input[name='service']:checked").length > 0;
The same goes to your HTML, but better to have an id to uniquely identify each of the checkboxes:
<input id="chk1" type="checkbox" name="service">
<br />
<input id="chk2" type="checkbox" name="service">
<br />
<input id="chk3" type="checkbox" name="service">
<br />
<input id="chk4" type="checkbox" name="service">
<br />
<input id="chk5" type="checkbox" name="service">
You can do the following way. Initially set a variable, lets say checked as false. Then set it to true if the following condition met. Use an if statement to check the variable. Take note: Here submit is the id of the button, main is the id of the form.
$("#submit").click(function() {
var checked = false;
if (jQuery('#main input[type=checkbox]:checked').length) {
checked = true;
}
if (!checked) {
//Do something
}
});

Change/Get check state of CheckBox

I just want to get/change value of CheckBox with JavaScript. Not that I cannot use jQuery for this. I've tried something like this but it won't work.
JavaScript function
function checkAddress()
{
if (checkAddress.checked == true)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onchange="checkAddress()" />
Using onclick instead will work. In theory it may not catch changes made via the keyboard but all browsers do seem to fire the event anyway when checking via keyboard.
You also need to pass the checkbox into the function:
function checkAddress(checkbox)
{
if (checkbox.checked)
{
alert("a");
}
}
HTML
<input type="checkbox" name="checkAddress" onclick="checkAddress(this)" />
You need to retrieve the checkbox before using it.
Give the checkbox an id attribute to retrieve it with document.getElementById(..) and then check its current state.
For example:
function checkAddress()
{
var chkBox = document.getElementById('checkAddress');
if (chkBox.checked)
{
// ..
}
}
And your HTML would then look like this:
<input type="checkbox" id="checkAddress" name="checkAddress" onclick="checkAddress()"/>
(Also changed the onchange to onclick. Doesn't work quite well in IE :).
I know this is a very late reply, but this code is a tad more flexible and should help latecomers like myself.
function copycheck(from,to) {
//retrives variables "from" (original checkbox/element) and "to" (target checkbox) you declare when you call the function on the HTML.
if(document.getElementById(from).checked==true)
//checks status of "from" element. change to whatever validation you prefer.
{
document.getElementById(to).checked=true;
//if validation returns true, checks target checkbox
}
else
{
document.getElementById(to).checked=false;
//if validation returns true, unchecks target checkbox
}
}
HTML being something like
<input type="radio" name="bob" onclick="copycheck('from','to');" />
where "from" and "to" are the respective ids of the elements "from" wich you wish to copy "to".
As is, it would work between checkboxes but you can enter any ID you wish and any condition you desire as long as "to" (being the checkbox to be manipulated) is correctly defined when sending the variables from the html event call.
Notice, as SpYk3HH said, target you want to use is an array by default. Using the "display element information" tool from the web developer toolbar will help you find the full id of the respective checkboxes.
Hope this helps.
You need this:
window.onload = function(){
var elCheckBox=document.getElementById("cbxTodos");
elCheckBox.onchange =function (){
alert("como ves");
}
};
Needs to be:
if (document.forms[0].elements["checkAddress"].checked == true)
Assuming you have one form, otherwise use the form name.
As a side note, don't call the element and the function in the same name it can cause weird conflicts.
<input type="checkbox" name="checkAddress" onclick="if(this.checked){ alert('a'); }" />
I know this is late info, but in jQuery, using .checked is possible and easy!
If your element is something like:
<td>
<input type="radio" name="bob" />
</td>
You can easily get/set checked state as such:
$("td").each(function()
{
$(this).click(function()
{
var thisInput = $(this).find("input[type=radio]");
var checked = thisInput.is(":checked");
thisInput[0].checked = (checked) ? false : true;
}
});
The secret is using the "[0]" array index identifier which is the ELEMENT of your jquery object!
ENJOY!
This is an example of how I use this kind of thing:
HTML :
<input type="checkbox" id="ThisIsTheId" value="X" onchange="ThisIsTheFunction(this.id,this.checked)">
JAVASCRIPT :
function ThisIsTheFunction(temp,temp2) {
if(temp2 == true) {
document.getElementById(temp).style.visibility = "visible";
} else {
document.getElementById(temp).style.visibility = "hidden";
}
}
var val = $("#checkboxId").is(":checked");
Here is a quick implementation with samples:
Checkbox to check all items:
<input id="btnSelectAll" type="checkbox">
Single item (for table row):
<input class="single-item" name="item[]" type="checkbox">
Js code for jQuery:
$(document).on('click', '#btnSelectAll', function(state) {
if ($('#btnSelectAll').is(':checked')) {
$('.single-item').prop('checked', true);
$('.batch-erase').addClass('d-block');
} else {
$('.single-item').prop('checked', false);
$('.batch-erase').removeClass('d-block');
}
});
Batch delete item:
<div class="batch-erase d-none">
<a href="/path/to/delete" class="btn btn-danger btn-sm">
<i class="fe-trash"></i> Delete All
</a>
</div>
This will be useful
$("input[type=checkbox]").change((e)=>{
console.log(e.target.checked);
});

Categories

Resources