How to select all values of checkbox when selectAll is selected? - php

I am trying to get all the id values of the selected checkboxes. When the user hits "selectAll", all the checkboxes are checked, but I just can't get their individual value. Any idea what I am doing wrong?
Here is the jQuery:
$(".selectAll").unbind("click").click(function(e){//needs work here
var bool = $(this).is(":checked"); //gets whether selected or not
var list = new Array();
$(function(){
$("input:checkbox").attr("checked", bool);
if(bool == true){
$.each((".delID :checked"),function(){
list.push( $(this).val());
alert( $(this).val());
}); }
});
}); //END of needs work area.
and here is the html:
<form name="selectDelete" class="selectDelete">
<table id="inboxTable" class="txt13" width="800px">
<tr><th align="left" style="text-decoration:underline"><input type="checkbox" name="selectAll" class="selectAll"/></th>
<th style="text-decoration:underline">To</th><td width="20px"></td>
<th style="text-decoration:underline">Subject
</th><td width="20px"></td>
<th style="text-decoration:underline">Date</th><td width="20px"></td>
<th style="text-decoration:underline">Action</th></tr>
<?php while($info=mysql_fetch_array($result)){
$id = $info['id']; ?>
echo "<tr>
<td width="20px"><input type="checkbox" name="delID" class="delID" value="'.$id.'"/></td>";
Just for anybody out there with similar problems, this is what I ended up doing to make the code work:
if(bool == true){
$(".delID").each(function(index,element){
//list.push( $(this).val());
alert(index + " " + $(this).val());
}); }
In my case, if 'bool == true', then all the checkboxes will ALWAYS be checked, so that's why using just .delID, instead of .delID :checked worked for me.
Thanks to all for the input.

You can use this code:
$(".delID:checked").each(function(){
list.push( $(this).val());
alert( $(this).val());
});
http://jsfiddle.net/ynhat/daQSM/

Related

Check and uncheck the checkbox by row

Good Day all...I'm having a multiple row which is fetched from my DB by foreach loop.
And I have 2 checkboxes in each row, What I'm trying is... If I check the 1st checkbox mean automatically the 2nd checkbox need to check.
For that I'm using ID to select that 2nd checkbox, Now because of that id is same for every row, if I select
1st row ,1st checkbox mean it's selecting all the second check box. But what I need is to get that particular selected row's 2nd checkbox need to be checked.
Anyone Help. Sorry for not sharing any live demo like jsfiddle. I hope u guys understand my problem.
<thead>
<th><input type="checkbox" id="select_all"></th>
</thead>
<?php foreach ($category_details as $key => $category_detail): ?>
<tr>
<td>
<input type="checkbox" class="checkbox" id="select_img" name="ids[]" value="<?php echo $category_detail['id'];?>"/>
<input type="checkbox" class="checkbox checkimg" name="imgs[]" value="<?php echo $category_detail['category_image'];?>"/>
</td>
<td>...</td> <!-- etc -->
</tr>
<?php endforeach ?>
$(document).ready(function(){
$('#select_all').on('click',function(){
if(this.checked){
$('.checkbox').each(function(){
this.checked = true;
});
}else{
$('.checkbox').each(function(){
this.checked = false;
});
}
});
$('#select_img').on('click',function(){
if(this.checked){
$('.checkimg').each(function(){
this.checked = true;
});
}else{
$('.checkimg').each(function(){
this.checked = false;
});
}
});
$('.checkbox').on('click',function(){
if($('.checkbox:checked').length == $('.checkbox').length){
$('#select_all').prop('checked',true);
}else{
$('#select_all').prop('checked',false);
}
});
});
You can use siblings jquery function. For example:
$('.whole_row').on('click',function(){
if(this.checked){
$(this).siblings().each(function(index, checkbox){
checkbox.checked = true;
});
}else{
$(this).siblings().each(function(index, checkbox){
checkbox.checked = false;
});
}
});
this way it will iterate the siblings tags and won't go outer the table rows. Just use classes not ids
Edit:
just a style note
$('.whole_row').on('click',function(){
let check = this.checked;
$(this).siblings().each(function(index, checkbox){
checkbox.checked = check;
});
});
html like this:
<tr>
<input type="checkbox" class="whole_row">one
<input type="checkbox">two
<input type="checkbox">three
<input type="checkbox">four
</tr>

Laravel: Jquery on click function issue

I am trying to alert something but on click function is running only once on the first button. but I have buttons on many rows.
I am fetching Data through Laravel from Database in a table. Only one button runs a function, then nothing happens with other buttons.
Jquery:
jQuery(document).ready(function(e) {
$('#restore-data').on('click', function(e) {
var val = $("#thisr").attr('value');
alert(val);
});
});
View:
<table id="recover-table" class="table" >
<thead>
<tr class="bg-info">
<th>Teacher Name</th>
<th>Date</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#foreach($trashs as $trash)
<tr id="thisr" value="{{$trash->id}}">
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap "><button type="submit" class="" name="id"
value="{{$trash->id}}" id="restore-data">Delete</button></td>
</tr>
#endforeach </tbody></table>
Right now even alert is not working, but I want to achieve Refresh table after a record is deleted from Table.
Update: Now Alert is working fine, but when I delete a record by pressing a button, only one row is deleting. the function runs once.
Complete Js:
jQuery(document).ready(function(e) {
$('#restore-data').on('click', function(e) {
let teacher_id=$(this).attr('value');
console.log('Restore button clicked!')
e.preventDefault();
$.ajax(
{
url: "/teachers/recover/" + $('#restore-data').attr("value"),
type: 'GET', // Just delete Latter Capital Is Working Fine
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: teacher_id,
success: function (data) {
console.log(data.msg);
console.log(teacher_id);
if(data.msg){
$('#thisr').remove();
$('#response').empty();
$(".toast").toast('show');
$('#response').append(data.msg);
}
},
error: function (xhr) {
console.log("Error Restoring Record");
//console.log(xhr.responseText);
},
});
});
});
You can try to use class 'restore-data'
$(document).ready(function(e) {
$(document).on('click', '.restore-data', function(e) {
var val = $('#thisr').val();
alert(val);
});
});
As id should be unique for each element.
You can try something like
#foreach($trashs as $trash)
<tr>
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap ">
<button type="button" data-trash-id="{{$trash->id}}" class="restore-data">Delete</button>
</td>
</tr>
#endforeach
and JS as
$(document).on('click', '.restore-data', function(e) {
var trash_id = $(this).attr('data-trash-id');
alert(trash_id);
});
Change this line.
var val = $("#thisr").attr('value');
to (since you have value attribute in button):
var val = $(this).attr('value');
or (since you have value attribute td):
var val = $(this).parent('tr#thisr').attr('value')
To remove a row.
$('#restore-data').on('click', function(e) {
var _this = $(this);
...
if(data.msg){
_this.parent('tr#thisr').remove();
....
Also change button type to button.
<button type="button" class="" name="id"
value="{{$trash->id}}" id="restore-data">Delete</button></td>
You gave same id to all button and id must be unique of particular button so you can define unique id with key of array and pass it to Function
#foreach($trashs as $key=>$trash)
<tr id="thisr{{$key}}">
<td class="text-nowrap ">{{$trash->efirst}} {{$trash->esecond}}</td>
<td class="text-nowrap ">{{$trash->deleted_at}}</td>
<td class="text-nowrap ">
<button type="button" class="" name="id" value="{{$trash->id}}" id="restore-data{{$key}}" onclick="restoreData({{$key}})">Delete</button>
</td>
</tr>
#endforeach
function restoreData(key){
var val = $("#restore-data"+key).attr('value');
alert(val);
// you can use either
$("#restore-data"+key).closest('tr').remove();
// OR
$('#thisr'+key).remove();
}

jQueryUI.Sortable update without using Ajax as normal form submit to PHP

I would like to sort a table with data row from MySQL then change the order and submit it.
I used jQueryUI.sortable to make those tr tag (row) draggable.
But when I submitting the form, some of them didn't changed order.
Why? I tried to figure it out, I var_dump the data I submitted and I found a problem:
The tr tag (row) I moved from the original order, won't pass to PHP so var_dump will not show the row ID.
To make it easier to understand, I post my code here:
HTML Code
<table>
<thead>
<tr>
<th>Subject</th>
<th>Content</th>
</tr>
</thead>
<tbody id="sortable">
<tr>
<td>
Hello World
<input name="displayorder[]" type="hidden" value="1" />
</td>
<td>I come from Mars!</td>
</tr>
<tr>
<td>
Hello Mars
<input name="displayorder[]" type="hidden" value="2" />
</td>
<td>I come from Jupiter!</td>
</tr>
<tr>
<td>
Hello StackOverflow
<input name="displayorder[]" type="hidden" value="3" />
</td>
<td>I come from North Korea ...</td>
</tr>
</tbody>
<tbody>
<tr>
<td colspan="2"><input type="submit" value="Submit!" />
</tr>
</tbody>
</table>
I omitted the form content cause it is not important
JavaScript (Sortable Library loaded)
$(document).ready(function() {
$('#sortable').sortable({
helper: fixHelper,
axis: 'y',
opacity: 0.6,
}).disableSelection();
});
var fixHelper = function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
};
PHP
$displayorder = $_POST["displayorder"];
if($displayorder != "") {
$order = 1;
foreach($displayorder as $value) {
mysql_query("UPDATE message SET displayorder=$order WHERE announcementid=$value");
$order++;
}
}
I will prefer not using Ajax to do this because I have dozens of similar page to do the same task.
Thanks in advance.
Well I decided to code it every page.
The code now:
JavaScript
$(document).ready(function() {
$('#sortable').sortable({
helper: fixHelper,
axis: 'y',
opacity: 0.4,
update: function(event, ui){
var data = $(this).sortable('serialize');
$.ajax({
data: data,
type: 'POST',
url: '/update.php?action=displayorder'
});
},
}).disableSelection();
});
var fixHelper = function(e, ui) {
ui.children().each(function() {
$(this).width($(this).width());
});
return ui;
};
PHP
foreach($_POST["displayorder"] as $i => $value) {
mysql_query("UPDATE message SET displayorder=$i WHERE announcementid=$value");
$i++;
}

JQuery - checkboxes dont't turn on

I'm having a problem with jquery.
I have a checkbox with ID "#checkAll" and checkboxes with class "checkboxes".
I'd like to turn all checkboxes on when the checkbox with ID "checkAll" is checked,
and I'd like to turn all checkboxes off when the checkbox with ID "checkAll" is checked off.
But, What's having now is that when I first click the checkbox(#checkAll), all other checkboxes are turned on and when I first turn the ckeckbox(#checkAll), all other checkboxs are turned off as well.
But, when I try to click the checkbox(#checkAll) in the second time, all other checkboxes are not turned on.
I don't know why this happens.
Please help me out!
This is my javascript handling events.
ADMIN.event = (function() {
function _init(){
$(function(){
var checkAll = $('#checkAll'),
checkboxes = $('.checkboxes');
checkAll.click(function(){
if($(this).is(':checked')){
checkboxes.attr('checked', 'checked');
} else {
checkboxes.removeAttr('checked');
}
})
});
}
_init();
}());
This is my view file in php.
<table class="fullTable">
<tr class="listTableTr">
<th class="listTableTh tinyTh"><input type="checkbox" name="" id="checkAll" /></th>
<th id="articleTitleTh" class="listTableTh">title</th>
</tr>
<?php foreach($postData as $post): ?>
<td class="listTableTd"><input type="checkbox" name="" class="checkboxes" /></td>
<td class="listTableTd"><?php echo $post['title'];?></td>
<?php endforeach; ?>
</table>
Try with .prop() like
checkAll.click(function(){
checkboxes.prop('checked',this.checked);
});
And its better to use even with .on() like
checkAll.on('click' , function(){
checkboxes.prop('checked',this.checked);
});
Try this :
$('#checkAll').on('click',function(){
if($("#checkAll").is(':checked')) {
$('.checkboxes').attr('checked',true);
} else {
$('.checkboxes').attr('checked',false);
}
});
DEMO
Try this
$("#checkAll").click(function () {
if ($(this).is(":checked"))
$(".checkboxes").prop("checked","checked");
else
$(".checkboxes").prop("checked",false);
});

ajax on click update form content

This is my form.
If i click the status content like progress or dsgs a textfield should appear. If i type text in it and click outside or press enter the old content should updated with the new one. I need it to be done with ajax and php. I am a beginner in php and ajax. Any reference or how can i do this?
This is my code for add status
$insert_task = "INSERT INTO `tbl_task` (`intProjectid`,`intUserid`,`dtDate`,`dtFinishdate`,`varIssue`,`varStatus`,`varNeedhelp` )VALUES ('".$id."','".$userid."','".$dtdate."','".$dtfinish."','".$issue."','".$status."','".$help."');";
$insert_query=mysql_query($insert_task);
You didn't give me anything but I've tried to implement something by guessing and hope if it doesn't solve your problem but at least it will help you. Following code is for your ajax functionality, you can put it inside the head tag of your page between script tags-
$(document).ready(function(){
var eventFlag=false;
var originalText='';
$('#mytable tr td span').click(function(e){
e.stopImmediatePropagation();
$(this).siblings().show().focus();
$(this).hide();
eventFlag=false;
originalText=$(this).siblings().val();
});
$('#mytable tr td input').blur(function(e){
if(!eventFlag && validate($(this))) doAjax($(this));
else
{
$(this).siblings().show();
$(this).hide();
}
});
$('#mytable tr td input').keypress(function(e){
e.stopImmediatePropagation();
var code = (e.keyCode ? e.keyCode : e.which);
if(code==13)
{
if(validate($(this)))
{
doAjax($(this));
eventFlag=true;
}
else
{
$(this).siblings().show();
$(this).hide();
}
}
});
function validate(input)
{
console.log(input.val()+" "+originalText);
if(input.val()!='' && input.val()!=originalText)
return true
else return false;
}
function doAjax(input)
{
var formData="proId="+input.attr('id')+"&text="+input.val();
$.ajax({
type: "POST",
url: "update.php",
data: formData,
success: function(data){
if(data==1)
{
input.siblings().text(input.val()).show();
input.hide();
}
else
{
input.siblings().show();
input.hide();
alert("something Wrong !");
}
},
error:function (xhr, ajaxOptions, thrownError){
alert("Error:"+xhr.status+" "+thrownError);
}
});
}
});
And I guessed your form could be something like this
<form action="#" method="post">
<table id="mytable">
<thead>
<tr>
<th>Issue</th><th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td>Login</td><td id="1"><span>Progress</span><input id="1" type="text" value="Progress" /></td>
</tr>
<tr>
<td>Something Else</td><td id="2"><span>Anything</span><input id="2" type="text" value="Anything"/></td>
</tr>
</tbody>
</table>
</form>
Put this inside your head or stylesheet (without style tag)
<style>
#mytable tr td input{display:none;}
</style>
And your update.php file should be something like
<?php
$proId = $_POST['proId'];
$text = $_POST['text'];
$update_task="update tbl_task set varStatus='".$text."' where intProjectid=".$proId;
if(mysql_query($update_task))
{
echo "1";
}
else
{
echo "0";
}
?>
I've tested it and working. The id I've used in the form is by assuming that you have id's for each of your status and you should update instead of inserting to change the status. let me know if it helps or if you need more help, I'll be on touch. Thanks!

Categories