Jquery changevalue or arraypush when checkbox are checked - javascript

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/

Related

How to disable anPHP disable and clear textbox when checkbox is unchecked. Check/uncheck checkbox depending on database

I want to disable and clear a textbox if a checkbox is uncheck and enable it when checked. At the same time, the checkbox should be dependent on the value on the database.
If deductstatus == 1, checkbox should be checked when loaded
If deductstatus == 2, checkbox should be unchecked when loaded
The code below is not working. Any help?
$(".dedstat").click(function() {
if ($(".dedstat").is(":checked")) {
$(".deductto").removeAttr("disabled")
} else {
$(".deductto").attr("disabled", "disabled")
var deductto = document.getElementById("deductto");
deductto.value = "";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="dedstat" id="dedstat" value="<?php if ($dedstat == 1) echo 'checked'; ?>">
<input type="text" name="deductto" id="deductto" value="<?php echo $deductto;?>">
Checked is not a value, it is an attribute, it should be:
<input type="checkbox" name="dedstat" id="dedstat" value="" <?php if ($dedstat == 1) echo 'checked'; ?>>
When manipulating boolean attributes such as checked, disabled, multiple, you should be using .prop() instead of .attr() or .removeAttr(). Some other suggested improvements:
Use this.checked instead of $(".dedstat").is(":checked"), so that it is context specific
Use the ID selector instead of class
You can chain your jQuery methods, so you can both disable the input and empty its value at the same time
Listen to the change event instead of click for <input> elements
$("#dedstat").change(function() {
if (this.checked) {
$("#deductto").prop("disabled", false)
} else {
$("#deductto")
.prop("disabled", true)
.val('');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="dedstat" id="dedstat">
<input type="text" name="deductto" id="deductto">
If you want the state of the input to be evaluated on pageload, you will also have to perform the same logic without binding it to the onChange event. The best way is to create a function that is called by both the onChange event and DOMready/window.load event. In the example below, the method we create will accept a DOM node as an argument, so that it is contextually aware of which checkbox element you are referring to:
// Method to conditionally enable/disable input
var updateTextInput = function(el) {
if (el.checked) {
$("#deductto").prop("disabled", false)
} else {
$("#deductto")
.prop("disabled", true)
.val('');
}
}
// Call method when change event is fired from checkbox
$("#dedstat").change(function() {
updateTextInput(this);
});
// Call method on DOMready, pass DOM node (not the jQuery object)
updateTextInput($('#dedstat')[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="dedstat" id="dedstat">
<input type="text" name="deductto" id="deductto">
And with regards to your PHP, you can simply use tenary operators to conditionally write the checked prop to your input element, i.e.:
<input type="checkbox" name="dedstat" id="dedstat" <?php echo $dedstat == 1 ? 'checked' : ''; ?>>
value attribute can not be used to keep it checked or unchecked based on database value. And bind checked or unchecked attribute separately.
So change that tag like this:
<input type="checkbox" name="dedstat" id="dedstat" onclick="isChecked()" value="1" <?php echo (isset($dedstat) && $dedstat == 1)? "checked" : "" ; ?>
More on this,
If you want to store 1 and 2 values to save checked and unchecked condition of the checkbox respectively, then what you should do is, if the checkbox is checked, you will get its value in php $_POST but if it was not checked, you will not get it in $_POST. So in that case, you should store its default value 2 into the DB column. So then only you can get 2 when you fetch its value next time from DB.
Just a little suggestion :
Is your JS at the bottom of the page ?
Plus I just noticed something :
$(".dedstat") <= you're calling a class with the dot. Your imputs have ID's.
$("#dedstat").click(function () {
if ($("#dedstat").is(":checked")) {
$("#deductto")
.removeAttr("disabled")
}
else {
$("#deductto")
.attr("disabled", "disabled")
var deductto = document.getElementById("deductto");
.deductto.value = "";
}
});
It should work a little better.

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

Changing input box also need to find check box checked or not in JS

I have input box along with checkbox in table <td> like below,
<td>
<input class="Comment" type="text" data-db="comment" data-id="{{uid}}"/>
<input type="checkbox" id="summary" title="Check to set as Summary" />
</td>
Based on check box only the content of input box will be stored in DB.
In the JS file, I tried like
var updateComment = function( eventData )
{
var target = eventData.target;
var dbColumn = $(target).attr('data-db');
var api = $('#api').val();
var newValue = $(target).val();
var rowID = $(target).attr('data-id');
var summary = $('#summary').is(':checked');
params = { "function":"updatecomments", "id": rowID, "summary": summary };
params[dbColumn] = newValue;
jQuery.post( api, params);
};
$('.Comment').change(updateComment);
But the var summary always returning false.
I tried so many ways prop('checked'),(#summary:checked).val() all are returning false only.
How to solve this problem?
Looks like you have multiple rows of checkboxes + input fields in your table. So doing $('#summary').is(':checked') will return the value of first matching element since id in a DOM should be unique.
So, modify your code like this:
<td>
<input class="Comment" type="text" data-db="comment" data-id="{{uid}}"/>
<input type="checkbox" class="summary" title="Check to set as Summary" />
</td>
And, instead of $('#summary').is(':checked'); you can write like this:
var summary = $(target).parent().find(".summary").is(':checked');
By doing this, we are making sure that we are checking the value of checkbox with the selected input field only.
Update: For listening on both the conditions i.e. when when checking checkbox first and then typing input box and when first typing input box and then checked:
Register the change event for checkbox:
// Whenever user changes any checkbox
$(".summary").change(function() {
// Trigger the "change" event in sibling input element
$(this).parent().find(".Comment").trigger("change");
});
You have missed the jQuery function --> $
$('#summary').is(':checked')
('#summary') is a string wrapped in Parentheses. $ is an alias for the jQuery function, so $('#summary') is calling jquery with the selector as a parameter.
My experience is that attr() always works.
var chk_summary = false;
var summary = $("#summary").attr('checked');
if ( summary === 'checked') {
chk_summary = true;
}
and then use value chk_summary
Change all the occurrences of
eventData
To
event
because event object has a property named target.
And you should have to know change event fires when you leave your target element. So, if checkbox is checked first then put some text in the input text and apply a blur on it, the it will produce true.
Use like this
var summary = $('#summary').prop('checked');
The prop() method gets the property value
For more details, please visit below link.
https://stackoverflow.com/a/6170016/2240375

My checkbox doesn't work with loop for to display data

I did the checkbox work good, this is my one:
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).prop("checked") == true){
document.getElementById("srt").value = document.getElementById("Ultra").value;
}
else if($(this).prop("checked") == false){
document.getElementById("srt").value = "";
}
});
});
At my display data part, I have the loop for to show all the record. I want after I click the checkbox the value I get from document.getElementById("Ultra").value and display on document.getElementById("srt").value. It work good at 1 record only, the rest I check didn't work. I think the problem is I display it on <input type="text" id="srt"> and the textbox I put in loop with loop for to display database. Any help?
This one is php part:
for ( $v = 0 ; $v < mysql_num_rows($result) ; $v++ )
{
$row = mysql_fetch_assoc($result);
?>
<td><input type="checkbox"/></td>
<?php
echo'<td>'.$row['aaa'].'</td>';
echo'<td>'.$row['bbb'].'</td>';
echo'<td>'.$row['ccc'].'</td>';
echo'<td><input type="text" id="srt"></td>';//////this one to display value i get
echo'<td>'.$row['dddr'].'</td>';
}
The value only display on 1 row only.
One thing I see is you have <input type="text" id="srt"> in each loop. This means your ids are not unique and this could cause problems in the document.getElementById("srt").value = document.getElementById("Ultra").value; call.
Try make ids unique (this means giving a different id for every textbox, maybe something like srt_'.$v.' and also retrieving the correct textbox id in the jquery function)
PS: can you please show also the "Ultra" input in your php code?
Edit: to get the correct textbox you could set an id to your checkbox too and use it to get the correct id of the textbox.
In your page:
echo'<td><input type="checkbox" id='.$v.'/></td>';
and
echo'<td><input type="text" id="srt'.$v.'"></td>';
And in your function
if($(this).prop("checked") == true){
document.getElementById("srt"+this.id).value = document.getElementById("Ultra").value;
}
I did not test it so there could be something to adjust, but the idea is there.
try this..
$(document).ready(function(){
var values = $('input.high_name:checked').map(function () {
return this.value;
}).get();
alert(values);
});
and your checkbox add class name,
<input type="checkbox" value="" name="high[]" class="high_name">

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