Get value checkbox javascript - javascript

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().

Related

How can I disable all checkboxes on webpage at once?

I have several sets of checkboxes on a webpage. I want to uncheck them all with javascript. Right now, I do it by looking for the names of each set and unchecking them with FOR loops like this...
for (i=0;i<document.getElementsByName("myboxes").length;i++) {
document.getElementsByName("myboxes")[i].checked=false;}
for (i=0;i<document.getElementsByName("moreboxes").length;i++) {
document.getElementsByName("moreboxes")[i].checked=false;}
for (i=0;i<document.getElementsByName("evenmoreboxes").length;i++) {
document.getElementsByName("evenmoreboxes")[i].checked=false;}
I'm looking for a way to target them all with one loop. I could do getElementsByTagName('input') to target all INPUTS, but that's a problem because I have some radio inputs that I don't want to uncheck. Is there a way to target all checkbox inputs?
Thanks for the suggestions. I just thought of something. Each NAME I use has the word "boxes" in it, myboxes, moreboxes, evenmoreboxes. Is there a way to target the word "boxes" in in the name, like a wildcard, something like document.getElementsByName("*boxes") that way if I add a set of checkboxes at some point that I don't want to uncheck I can simply name them differently.
You can select all checked checkboxes and reset their state:
function uncheckAll() {
document.querySelectorAll('input[name$="boxes"]:checked')
.forEach(checkbox => checkbox.checked = false);
}
<input type="checkbox"/>
<input type="checkbox" name="a_boxes" checked/>
<input type="checkbox"/>
<input type="checkbox" name="b_boxes" checked/>
<input type="checkbox" name="c_boxes" checked/>
<button onclick="uncheckAll()">Reset</button>
you can use document.querySelectorAll('input[type="checkbox"]'); to get a list of them all. then run your loop
My proposal is:
document.querySelectorAll("[name=myboxes], [name=moreboxes], [name=evenmoreboxes]").forEach((e) => echecked=false);
document.querySelectorAll("[name=myboxes], [name=moreboxes], [name=evenmoreboxes]").forEach((e) => e.checked=false);
<input type="checkbox" name="myboxes" value="1" checked>1<br>
<input type="checkbox" name="moreboxes" value="2" checked>2<br>
<input type="checkbox" name="evenmoreboxes" value="3" checked>3<br>
As suggested by #imjared, you can use querySelectorAll, but you will have to iterate over it:
querySelectorAll('input[type="checkbox"]').forEach(c => c.checked = false);
Here is the doc for querySelectorAll

jquery value from checkbox in loop not posting

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">

jQuery lookup from databound checklist

My MSCRM 2015 online solution uses a 3rd party tool to build a checkbox list from N:N dynamically and this is then published in another Iframe, I was wandering if I could use jQuery to test if any of these checkboxes are checked in JavaScript
Problem though if you look at the html these inputs don't have id's or names I can use to reference them with something like ...
var checkboxValues = [];
$('input[name=checboxset_ava_incident_ava_affectedcountry]:checked').map(function() {
checkboxValues.push($(this).val());
Here is an example of how the html get build:
hope the sizing is ok to read But what I want you to see is the <input> tag's properties:
<input type="checkbox" data-bind="id: Id, checked: Value, title: Name, enable: $parent.GetIsEnabled()">
If you want to find selected checkboxes, radio buttons or select elements, look at the jQuery :checked selector, as in
$(':checked')...
If you want checkboxes, use the type attribute in your selector, as in
$('input[type=checkbox]')...
or combine them, to find only checked checkboxes (i.e., to ensure that you don't pick up any radio buttons or select elements):
$('input[type=checkbox]:checked')...
DEMO
var findChecked = function() {
var checked_values = [];
var $checkedBoxes = $('input[type=checkbox]:checked');
console.log('$checkedBoxes', $checkedBoxes.length);
$checkedBoxes.each(function(i, e) {
checked_values.push($(e).val());
});
alert(checked_values);
};
$('button').click(findChecked);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label><input type="checkbox" checked value="1" /> 1</label>
<label><input type="checkbox" value="2" /> 2</label>
<label><input type="checkbox" value="3" /> 3</label>
<button>See checked</button>

Need JQuery to mark checkboxes checked from list/array from database

Using SQL 2008 Server and the latest JQuery. If I query a column from the database and get the list/array how do I mark the checkboxes in each checkbox group 'checked'? Example checkbox groups and lists below:
list for category '1,7,20' (Jquery should mark checkboxes with values 1,7,10 checked)
list for likes '2,3' (Jquery should mark checkboxes with values 2 and 3 checked)
<form>
<input type="checkbox" class="category" name="category" value="14" />Blah
<input type="checkbox" class="category" name="category" value="1" />Blah1
<input type="checkbox" class="category" name="category" value="7" />Blah2
<input type="checkbox" class="category" name="category" value="20" />Blah3
<input type="checkbox" class="likes" name="likes" value="17" />Apple
<input type="checkbox" class="likes" name="likes" value="3" />Apple1
<input type="checkbox" class="likes" name="likes" value="2" />Apple2
<input type="checkbox" class="likes" name="likes" value="13" />Apple3
</form>
I tried the following JQuery code, but it doesn't work:
$.each(['1,7,20'], function (index, item) {
if ($('.category').val() === item) {
$(".category").prop("checked", true);
}
});
You're passing an array with a single element that is the string 1,7,20, not an array with three elements that are the strings 1,7 and 20, so I'm not sure why you're expecting it to work. If your input is in fact the string, you can split it on the comma to get an array with your numbers as strings:
var myString = '1,7,20';
var myArray = myString.split(',');
Then pass myArray to the $.each() function call.
There's also a problem with the code inside the function you've passed to $.each(). If you do call .val() on a jQuery object containing multiple elements, it will usually return the value for the first element only. You'll need to iterate again over the collection of elements, and use this to refer to the current element.
$.each(myArray, function(index, item){
$('.category').each(function(){
if(this.value === item) {
this.checked = true;
}
});
});
By the way, semantically, you should be using a filter. You can do the same thing while simultaneously increasing the readability of your code.

jQuery Store Values of checkboxes in div

How can I get this list of checkboxes to be added to a div prior to their selected state, so if they are selected, they should be added to the div, if not they are removed from the list if not selected.
<div id="selected-people"></div>
<input type="checkbox" value="45" id="Jamie" />
<input type="checkbox" value="46" id="Ethan" />
<input type="checkbox" value="47" id="James" />
<input type="checkbox" value="48" id="Jamie" />
<input type="checkbox" value="49" id="Darren" />
<input type="checkbox" value="50" id="Danny" />
<input type="checkbox" value="51" id="Charles" />
<input type="checkbox" value="52" id="Charlotte" />
<input type="checkbox" value="53" id="Natasha" />
Is it possible to extract the id name as the stored value, so the id value will be added to the div instead of the value - the value needs to have the number so that it gets added to a database for later use.
I looked on here, there is one with checkboxes and a textarea, I changed some parts around, doesn't even work.
function storeuser()
{
var users = [];
$('input[type=checkbox]:checked').each(function()
{
users.push($(this).val());
});
$('#selected-people').html(users)
}
$(function()
{
$('input[type=checkbox]').click(storeuser);
storeuser();
});
So you want to keep the DIV updated whenever a checkbox is clicked? That sound right?
http://jsfiddle.net/HBXvy/
var $checkboxes;
function storeuser() {
var users = $checkboxes.map(function() {
if(this.checked) return this.id;
}).get().join(',');
$('#selected-people').html(users);
}
$(function() {
$checkboxes = $('input:checkbox').change(storeuser);
});​
Supposing you only have these input controls on page I can write following code.
$.each($('input'), function(index, value) {
$('selected-people').append($(value).attr('id'));
});
Edited Due to More Description
$(document).ready(function() {
$.each($('input'), function(index, value) {
$(value).bind('click', function() {
$('selected-people').append($(value).attr('id'));
});
});
});
Note: I am binding each element's click event to a function. If that doesn't work or it isn't a good for what you are supposed to do then change it to on "change" event.
Change:
users.push($(this).val());
to:
users.push($(this).attr('id'));
This is for to bind the comma seperated values to input checkbox list
$(".chkboxes").val("1,2,3,4,5,6".split(','));
it will bind checkboxes according to given string value in comma seperated.

Categories