Getting values of hidden checkboxes jQuery - javascript

I have a form with several checkboxes. Some values need to be true by default so i have made them hidden as:
<input type=checkbox name="<%= _key %>" checked="checked" style="display:none" />
To retrieve all values i'm doing:
var form_data = {}
$('form').find("input").each(function(i, e) {
if (e.checked)
form_data[e.name] = e.value;
});
But the hidden input fields are not coming. What am I doing wrong? How can I correct it?
Also im using underscore.js but i don't think this problem has to do anything with it.

For simplicity you can do this:
$(function(){ // put the code in doc ready
var form_data = {}
$('form').find(":checkbox:checked").each(function(i, e) {
form_data[e.name] = e.value;
});
});
So here i am suggesting you to just loop through the checked elems and put names & values in the javascript object.
But if you are interested in only hidden checked checkboxes $('form').find(":checkbox:checked:hidden").

I think you should do this jQuery way.
$('form').find("input").each(function(i, e) {
var jEl = $(this);
if(jEl.is(":checked"))
alert(1);
alert(jEl.attr("name"));
});

Related

How do I access input name in php code through Javascript?

I have a PHP form with some rows. These rows have fields which look like this:
<input type="text" name="addresses[n][0]" value="mail " id="address" class="validate">
I have the following code in Javascript to add and and delete rows:
$(document).ready(function () {
$('select').material_select();
});
$(function ()
{
$(document).on('click', '.btn-add', function (e)
{
e.preventDefault();
var controlForm = $('.controls form:first'),
currentEntry = $(this).parents('.entry:first'),
newEntry = $(currentEntry.clone()).appendTo(controlForm);
newEntry.find('input').val('');
}).on('click', '.btn-remove', function (e)
{
$(this).parents('.entry:first').remove();
e.preventDefault();
return false;
});
});
My problem is, that after sending this form in POST with added rows, the added ones have the same 'n' index, because they are cloned. How can I access the 'name' attribute of them in the newEntry variable, which is a div of the whole row?
I have tried things like
newEntry.find('name').val('addressesNewName')
newEntry.find('input').getAttribute('name') = 'addressesNewName'
newEntry.find('name').setAttribute("name","addressesNewName");
newEntry.find('input').find('name').val('addressesNewName');
newEntry.find('input').attr('name') = 'newaddresses';
newEntry.find('input').attr('name').val('newaddresses');
But nothing changes the name in the field.
I don't need help with what n values to assign and so on, only how to change the name of the input field.
Have you tried?
newEntry.attr('name', 'addressesNewName');
Since you're using jQuery, accessing node attributes is easily done via:
$(node).attr('attributeName'); // get attribute value
$(node).attr('attributeName', 'newValue'); // set attribute value
jQuery API

How do I add radial/checkbox values to an object using jQuery?

So I'm trying to iterate through all the values of an HTML form and store them in a hashtable object of sorts.
The HTML for the form is pretty lengthy so I won't paste that here. But here is my JavaScript/jQuery so far:
readForm = function () {
var formValues = {};
$('form :input').each(function () {
var input = $(this);
formValues[input.attr('name')] = input.val();
});
console.log(formValues);
}
When I put these values in the form:
https://res.cloudinary.com/merrickcloud/image/upload/v1542089140/fdsa_z9re1e.png
I get this in the console:
https://res.cloudinary.com/merrickcloud/image/upload/v1542089140/fdsafsdaf_tmdib6.png
Why is the value on the radial and checkbox inputs incorrect? And what is that last undefined property?
For checkboxes you can use this:
Option 1:
$('#checkbox_id').prop('checked'));
Option 2:
$('#checkbox_id').is(':checked'));
Maybe in your case with the loop you can try this:
if(input.attr('type') == 'checkbox') {
input.is(':checked'));
}
...
The undefined property is maybe the Submit button. Is it like this?
<input type="submit" value="Submit Profile">

Jquery changevalue or arraypush when checkbox are checked

I have input like this(Looping input form) :
<input id="check_<?php echo $value->id; ?>" value="<?php echo $value->id; ?>" type="checkbox" checked class="check_table get-report-filter">
and hidden input like this :
<input class="hiddenakun" type="hidden" name="hiddenakun" />
this my jquery :
var akun = [];
$('.get-report-filter').each(function() {
$('.get-report-filter').on('click', function() {
akun.push($(this).val());
}
});
my point is, I want to push each array data checked to .hiddenakun, but my code not working, I know it cause every time I write wrong code, datepicker wont work.
You can use .map() along with .get() to create an array of :checked checkboxes values
var akun = $('.get-report-filter:checked').map(function(){
return $(this).val();
}).get();
//Set hidden value
$('.hiddenakun').val(akun.join(','));
If you want to set the value of checked event, then bind an event handler
var elems = $('.get-report-filter');
elems.on('change', function() {
var akun = elems.filter(':checked').map(function(){
return $(this).val();
}).get();
//Set hidden value
$('.hiddenakun').val(akun.join(','));
});
Note, datepicker wont work. it's due to syntax error.
Try this:
$('.get-report-filter').each(function(){
if($(this).is(':checked'))
{
akun.push($(this).val());
}
});
// It will push the checked checkbox values to akun
You need more strict checker finder. Not all checkbox, but checked checboxes. For this purpose you can use pseudo class finder
$('.get-report-filter:checked').each
Find info here
https://api.jquery.com/checked-selector/

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);
});

Select values of checkbox group with jQuery

I'm using Zend_Form to output a set group of checkboxes:
<label style="white-space: nowrap;"><input type="checkbox" name="user_group[]" id="user_group-20" value="20">This Group</label>
With a normal HTTP Post these values are passed as an array, but when I'm somewhat stumped on how to grab all the values using jQuery. I figured I can select the group using:
$("input[#name='user_group[]']").val()
but that just grabs the value of the first checkbox in the list regardless of if it is checked of not. Any ideas?
You could use the checked selector to grab only the selected ones (negating the need to know the count or to iterate over them all yourself):
$("input[name='user_group[]']:checked")
With those checked items, you can either create a collection of those values or do something to the collection:
var values = new Array();
$.each($("input[name='user_group[]']:checked"), function() {
values.push($(this).val());
// or you can do something to the actual checked checkboxes by working directly with 'this'
// something like $(this).hide() (only something useful, probably) :P
});
I'm not sure about the "#" used in the selector. At least with the latest jQuery, I had to remove the # to get this to function with two different checkbox arrays, otherwise all checked items were selected for each array:
var items = [];
$("input[name='items[]']:checked").each(function(){items.push($(this).val());});
var about = [];
$("input[name='about[]']:checked").each(function(){about.push($(this).val());});
Now both, items and about work.
Use .map() (adapted from the example at http://api.jquery.com/map/):
var values = $("input[name='user_group[]']:checked").map(function(index,domElement) {
return $(domElement).val();
});
With map in instead of each it is possible to avoid the array creation step:
var checkedCheckboxesValues =
$('input:checkbox[name="groupName"]:checked')
.map(function() {
return $(this).val();
}).get();
From the map() page of the docs:
Pass each element in the current matched set through a function, producing a new jQuery object containing the return values
get() turns those values into an array.
mhata dzenyu mese. its actually
var selectedGroups = new Array();
$(".user_group[checked]").each(function() {
selectedGroups.push($(this).val());
});
I just shortened the answer I selected a bit:
var selectedGroups = new Array();
$("input[#name='user_group[]']:checked").each(function() {
selectedGroups.push($(this).val());
});
and it works like a charm, thanks!
I'm not 100% entirely sure how you want to "grab" the values. But if you want to iterate over the checkboxes you can use .each like so:
("input[#name='user_group[]']").each( function() {
alert($(this).val());
});
Of course a better selector is available:
$(':checkbox')
var values = $("input[name='user_group']:checked").map(function(){
return $(this).val();
}).get();
This will give you all the values of the checked boxed in an array.
You can have a javascript variable which stores the number of checkboxes that are emitted, i.e in the <head> of the page:
<script type="text/javascript">
var num_cboxes=<?php echo $number_of_checkboxes;?>;
</script>
So if there are 10 checkboxes, starting from user_group-1 to user_group-10, in the javascript code you would get their value in this way:
var values=new Array();
for (x=1; x<=num_cboxes; x++)
{
values[x]=$("#user_group-" + x).val();
}
$(document).ready(function(){
$('#btnskillgroup').click(function(){
getCheckedGroups('skills');
});
$('#btncitiesgroup').click(function(){
getCheckedGroups('cities');
});
var getCheckedGroups = function(groupname){
var result = $('input[name="'+groupname+'"]:checked');
if (result.length > 0) {
var resultstring = result.length +"checkboxes checked <br>";
result.each(function(){
resultstring += $(this).val()+" <br>"; //append value to exsiting var
});
$('#div'+groupname).html(resultstring);
}else{
$('#div'+groupname).html(" No checkbox is Checked");
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
Skills:<input type="checkbox" name="skill" value="Java"> Java
<input type="checkbox" name="skill" value="Jquery"> Jquery
<input type="checkbox" name="skill" value="PHP"> PHP
<br>
<input type="checkbox" name="cities" value="Pune"> Pune
<input type="checkbox" name="cities" value="Baramati"> Baramati
<input type="checkbox" name="cities" value="London"> London
<input type="submit" id="btnskillgroup" value="Get Checked Skill group">
<input type="submit" id="btncitiesgroup" value="Get cities checked group">
<div id="divskills"></div>
<div id="divcities"></div>

Categories

Resources