onChange Checkbox Highlight Row - javascript

I'm trying to use a script that I thought would be incredibly useful but I must not be getting it. All it is is a simple check the box, highlight the row kind of script but I'm getting stuck somewhere.
$(document).ready(function() {
$("input[type='checkbox']").on('change', function() {
if ($(this).is(":checked")) {
$(this).closest('tr').addClass("highlight");
} else {
$(this).closest('tr').removeClass("highlight");
}
});
});
.highlight {
background-color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input id="checkboxSelect" type="checkbox"></td>
<td>231540</td>
<td>2018-02-25 00:00:00</td>
<td>93.50</td>
</tr>
<table>
So when the checkbox of that particular row is checked I want to be able to add the class "highlight" to that checkbox's table row.
UPDATED //
I have also tried one of the suggested answers with the following script:
$("#checkboxSelect").click(function(){
if ($(this).is(":checked")){
$(this).parent().parent().removeClass("highlight");
alert('hello');}
else{
$(this).parent().parent().addClass("highlight");
alert('goodbye');}
});
It still won't fire, I have tested it on jsFiddle and it does work there, but in my environment it just won't fire.
In case it means anything this is technically how these rows are generated:
$.ajax({
type:'GET',
url: '/customers/details/openInvoices',
dataType:'json',
data: {
'customerID': $('select[name=payer_id]').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function () {
$('#createOrigin').modal('show');
toastr.error('Check your inputs!', 'Error Alert', {timeOut: 5000});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
$.each(data, function(i,val) {
$('<tr>').append(
$('<td>').html('<input type="checkbox" class="checkboxSelect">'),
$('<td>').text(val.pro_number),
$('<td>').text(val.due_date),
$('<td>').text(val.balance)).appendTo('#customerOpenInvoicesTable');
$('#openInvoicesOverlay').html('');
$('#openInvoicesOverlay').removeClass('overlay');
});
}
}
});

use jquery..
And don't forget to add jquery cdn......
$("#checkboxSelect").click(function(){
if ($(this).is(":checked")){
$(this).parent().parent().removeClass("highlight")}
else{
$(this).parent().parent().addClass("highlight")}
});
That will do it...

Related

Can't delete data after 10 entries in AJAX, JQuery and javascript/php

I have 10 rows with data inserted and I'm able to delete any of those, but after I insert from 11th row onwards I can't delete any of the rows after the 10th.
EDIT (I CAN'T DELETE ANYTHING WHEN THE RESPONSIVE FORM IS SHOWING)
$(document).ready(function(){
$('#list').dataTable({
responsive: true
});
$('.delete_piece').click(function(){
_conf("Are you sure to delete this piece?","delete_piece",[$(this).attr('data-id')])
})
})
function delete_piece($id){
start_load()
$.ajax({
url:'ajax.php?action=delete_piece',
method:'POST',
data:{id:$id},
success:function(resp){
if(resp==1){
alert_toast("Data successfully deleted",'success')
setTimeout(function(){
location.reload()
},1500)
}
}
})
}
DELETE FUNCTION AJAX
if($action == "delete_piece"){
$delsete = $crud->delete_piece();
if($delsete)
echo $delsete;
}
DELETE FUNCTION FOR THE ADMIN (ME)
function delete_piece(){
extract($_POST);
$delete = $this->db->query("DELETE FROM mro_inventory where id = ".$id);
if($delete){
return 1;
}
}
Consider the following.
$(function() {
function delete_piece($id) {
start_load()
$.ajax({
url: 'ajax.php?action=delete_piece',
method: 'POST',
data: {
id: $id
},
success: function(resp) {
if (resp == 1) {
alert_toast("Data successfully deleted", 'success')
setTimeout(function() {
location.reload()
}, 1500);
}
}
});
}
$('#list').dataTable({
responsive: true
});
$('tbody').on("click", ".delete_piece", function(e) {
_conf("Are you sure to delete this piece?", "delete_piece", [$(this).attr('data-id')])
});
});
This uses the .on() method to delegate the click event to a class.
Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated event handlers to avoid the need to frequently attach and remove event handlers.
See more: https://api.jquery.com/on/
It was not clear from your post what the HTML structure looks like; yet, you are using DataTables, so I know there should be a Table Body element that should be present.
this is how I solved the problem!!
$(document).ready(function() {
$('#list').dataTable({
responsive: true
});
$('tbody').on("click", ".delete_piece", function() {
_conf("Are you sure to delete this piece?","delete_piece",[$(this).attr('data-id')])
})
})
function delete_piece($id){
start_load()
$.ajax({
url: 'ajax.php?action=delete_piece',
method: 'POST',
data: {
id:$id
},
success: function(resp) {
if (resp == 1) {
alert_toast("Data successfully deleted",'success')
setTimeout(function() {
location.reload()
}, 1500)
}
}
})
}

AJAX/jQuery generated inputs not recognized by other jQuery scripts

I have what I assume is a relatively simple issue. For testing purposes I have made it so simple so as to locate the issue.
I have a jQuery script that works alongside AJAX to return some results next to checkboxes, here it is below:
$.ajax({
type:'GET',
url: '/customers/details/emails',
dataType:'json',
data: {
'customerID': $('select[name=payer_id]').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function () {
$('#createOrigin').modal('show');
toastr.error('Check your inputs!', 'Error Alert', {timeOut: 5000});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
$.each(data, function(i,val) {
$('<tr>').append(
$('<td>').html('<input type="checkbox" id="emailCheckboxSelect">'),
$('<td>').text(val)).appendTo('#customerEmails');
});
}
}
});
As you can see near the end, for each result a table row is appended, with a checkbox with an id of "emailCheckboxSelect".
Now to my problem, these are obviously dynamically created elements so I believe this is the issue with this script (a simple dummy just to locate the issue). Here is that script that should work:
$(function(){
$('#emailCheckboxSelect').click(function(){
alert('clicked');
});
});
This doesn't work with the dynamically created elements. However, I did add <input type="checkbox" id="emailCheckboxSelect">Checkbox directly to my page, and this does set off the alert.
So what am I doing wrong and what do I need to do so that jQuery can recognize dynamically created elements?
Try to bind the click event after the $.each(data, function() {}) inside the sucess: function() {}
You are using multiple elements with same id in the DOM : Element IDs should be unique within the entire document.
use classes instead
your code will look like:
$.ajax({
type: 'GET',
url: '/customers/details/emails',
dataType: 'json',
data: {
'customerID': $('select[name=payer_id]').val(),
'_token': $('input[name=_token]').val(),
},
success: function(data) {
$('.errorTitle').addClass('hidden');
$('.errorContent').addClass('hidden');
if ((data.errors)) {
setTimeout(function() {
$('#createOrigin').modal('show');
toastr.error('Check your inputs!', 'Error Alert', {
timeOut: 5000
});
}, 500);
if (data.errors.title) {
$('.errorTitle').removeClass('hidden');
$('.errorTitle').text(data.errors.title);
}
if (data.errors.content) {
$('.errorContent').removeClass('hidden');
$('.errorContent').text(data.errors.content);
}
} else {
$.each(data, function(i, val) {
$('<tr>').append(
$('<td>').html('<input type="checkbox" class="emailCheckboxSelect" />'),
$('<td>').text(val)).appendTo('#customerEmails');
});
$('.emailCheckboxSelect').click(function(e) {
alert('clicked');
});
}
}
});
Try changing your click event to something like
$('td').on('click', '.emailCheckboxSelect', function () {
alert('clicked');
});
This would work on dynamically created elements. Also, use class instead of id for dynamically created elements.

Displaying delete icon when checkbox is selected - JS

I am trying to do this, when a user checks at least one box, the icon must show if not, it hides.
With my code, when i select the #mastercheckbox, the icon does show but when i select the other checkbox displaying on each row, it doesn't show.
Why is this happening?
HTML:
<table id="users-table" class="table table-hover table-condensed" style="width:100%">
<thead>
<tr>
<th><input type="checkbox" id="master"></th>
<th>Category</th>
<th>Description</th>
<th>Number of Items</th>
<th>Action</th>
</tr>
</thead>
</table>
<script type="text/javascript">
$(document).ready(function() {
oTable = $('#users-table').DataTable({
"processing": true,
"serverSide": true,
"bProcessing":false,
"bSort":false,
"ajax": "{{ route('datatable.getcategories') }}",
"columns": [
{data: 'checkbox', name: 'checkbox', orderable: false, searchable: false},
{data: 'name', name: 'name'},
{data: 'action', name: 'action', orderable: false, searchable: false}
],
});
});
</script>
Controller:
$stduents= Student::all();
return Datatables::of($student)->addColumn('checkbox', function ($std) {
return '<input type="checkbox" class="sub_chk" data-id="'.$std->id.'">';
})->make(true);
Where i select my checkbox:
<script type="text/javascript">
$(document).ready(function () {
$("i[type='icon']").css('display','none'); //set style explicitly
$('#master').on('click', function(e) {
if($(this).is(':checked',true))
{
$(".sub_chk").prop('checked', true);
} else {
$(".sub_chk").prop('checked',false);
}
});
$('.delete_all').on('click', function(e) {
var allVals = [];
$(".sub_chk:checked").each(function() {
allVals.push($(this).attr('data-id'));
});
if(allVals.length <=0)
{
alert("Please select row.");
}
else {
var check = confirm("Are you sure you want to delete this row?");
if(check == true){
var join_selected_values = allVals.join(",");
$.ajax({
url: $(this).data('url'),
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: 'ids='+join_selected_values,
success: function (data) {
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
location.reload();
alert(data['success']);
}
else if (data['error'])
{
alert(data['error']);
}
else
{
//alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
$.each(allVals, function( index, value )
{
$('table tr').filter("[data-row-id='" + value + "']").remove();
});
}
}
});
$('[data-toggle=confirmation]').confirmation({
rootSelector: '[data-toggle=confirmation]',
onConfirm: function (event, element) {
element.trigger('confirm');
}
});
$(document).on('confirm', function (e) {
var ele = e.target;
e.preventDefault();
$.ajax({
url: ele.href,
type: 'GET',
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
success: function (data) {
if (data['success'])
{
$("#" + data['tr']).slideUp("slow");
location.reload();
alert(data['success']);
}
else if (data['error']) {
alert(data['error']);
}
else
{
alert('Whoops Something went wrong!!');
}
},
error: function (data) {
alert(data.responseText);
}
});
return false;
});
});
</script>
Display icon when at least one checkbox is selected:
<script>
$("input[type='checkbox']").click(function() {
var atLeastOneChecked = false;
$("input[type='checkbox']").each(function(index) {
if ($(this).prop('checked'))
atLeastOneChecked = true;
});
if (atLeastOneChecked) {
$("i[type='icon']").show(); //built-in jquery function
//...or...
$("i[type='icon']").css('display','inline-block'); //or set style explicitly
} else {
$("i[type='icon']").hide(); //built-in jquery function
//...or...
$("i[type='icon']").css('display','none'); //set style explicitly
}
});
</script>
Since your checkboxes are added after the page load $("input[type='checkbox']").click(...) will not add the event handler to them. i.e.
//will handle clicked events on checkbox existing when this js runs
$('input[type="checkbox"]').click(function() {
alert('clicked')
});
//will handle clicked events on dynamically added checkboxes
$(document).on('click', 'input[type="checkbox"]', function() {
alert('clicked2');
});
//add new checkbox to page
$('button').click(function() { $('#master').after($('<input type="checkbox" >')) });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" id="master">
<button type='button'>Add Checkbox</button>
What you want to do instead is $(document).on('click', 'input[type="checkbox"]', function() { ... }
A simple example works for me - whatever is going wrong for you, you'll have to either provide more code or narrow in on the problem with some debugging of your own.
Hope this helps: master and grouped checkboxes all react to click
HTML:
<div id="icon">SEE ME?</div>
<div id="info">Information</div>
<div><input type="checkbox" id="master"></div>
<div><input type="checkbox" name="subset01[]" value="00"></div>
<div><input type="checkbox" name="subset01[]" value="01"></div>
<div><input type="checkbox" name="subset01[]" value="02"></div>
<div><input type="checkbox" name="subset01[]" value="03"></div>
<div><input type="checkbox" name="subset01[]" value="04"></div>
<div><input type="checkbox" name="subset01[]" value="05"></div>
<div><input type="checkbox" name="subset01[]" value="06"></div>
<div><input type="checkbox" name="subset01[]" value="07"></div>
<div><input type="checkbox" name="subset01[]" value="08"></div>
<div><input type="checkbox" name="subset01[]" value="09"></div>
CSS:
#icon{ display: none; }
JS:
$( function(){
$('#info').text("please click a checkbox");
$( "input[type='checkbox']" ).click( function(){
$('#info').html( "you clicked # "+ new Date().getTime() +" currently "+ $(':checked').length +" checked" );
if( $(':checked').length ){
$("#icon").show();
}else{
$("#icon").hide();
}
} );
} );

Animate TR to disappear on ajax request

I am using bootbox to create the following modal:
$("a.delete").on("click", function() {
var id = $(this).attr('id').replace('item_', '');
var parent = $(this).parent().parent();
var table = $(this).attr('rel');
bootbox.dialog({
message: "Are you sure you want to delete this entry?",
title: "Delete Confirmation",
buttons: {
success: {
label: "Yes",
className: "btn-danger",
callback: function() {
$.ajax({
type: "POST",
url: "",
data: 'deleteItem=' + id + '&table=' + table,
beforeSend: function () {
parent.animate({
'backgroundColor': '#E3E3E3'
}, 400);
},
success: function (msg) {
if (msg == "success") {
$('#projects').DataTable().row(parent).remove().draw();
$("html, body").animate({
scrollTop: 0
}, 600);
count();
} else if (msg == 'last') {
$('#rld_div').load("<?php echo $_SERVER['REQUEST_URI']; ?> #rld_div");
} else {
bootbox.alert(msg);
}
count();
}
});
}
},
danger: {
label: "No",
className: "btn-primary"
},
}
});
});
HTML:
Delete Project
It strips the id from the id of the <a> and and gets the name of the table from the rel. Everything seems to be working but the parent (namely the tr), will not animate and just disappears
When I log the var parent I get this [tr.odd, prevObject: m.fn.init[1], context: a#item_250558768.delete] so it seems to be selecting the right object. What am I doing wrong?
If you're after the closest parent <tr> (assuming your link is in a table row), just use parents('tr') (note the 's').
As far as the animation goes, I'm not sure that beforeSend will let you modify the DOM - the manual makes it seem like it's purpose is to allow you to modify the XMLHttpRequest object before the request it made. It might make more sense to move your animation outside the ajax request, and make the request in the "complete" callback for the animation.
If that seems workable, you can also somewhat simply your code by using the $.post helper instead of $.ajax:
parent.animate({ 'backgroundColor': '#E3E3E3' },
400,
function(){
var data = {
deleteItem : id,
table: table
};
$.post(url, data)
.done(function (msg, jhr, status) {
if (msg == "success") {
$('#projects').DataTable().row(parent).remove().draw();
$("html, body").animate({
scrollTop: 0
}, 600);
count();
} else if (msg == 'last') {
$('#rld_div').load("<?php echo $_SERVER['REQUEST_URI']; ?> #rld_div");
} else {
bootbox.alert(msg);
}
count();
});
});

Form doesn't submit form data populated via AJAX

I'm having the following problem with my code below: when 'productSearchResult' is populated via AJAX, the contents are not included when the form is submitted using the 'Add' button.
UPDATE 1:
Strangely it is working, but only the first time productSearchQuery is populated. Any subsequent populations of productSearchQuery run into the problem above.
HTML:
<form name="productSearch">
<input name="productSearchQuery" type="textbox">
</form>
<form name="productAdd">
<div id="productSearchResult"></div>
</form>
<a>Add</a>
<div id="addResult"></div>
HTML loaded via AJAX into productSearchResult:
<input type="radio" name="productId" value="3944">
<input type="radio" name="productId" value="3946">
<input type="radio" name="productId" value="3999">
JS:
<script type="text/javascript">
function postData(type, url, data, targetDiv) {
$.ajax({
type: type,
url: url,
data: data,
success: function(response) {
$(targetDiv).html(response);
},
error: function() {
alert('Error! Plese try again.');
}
});
return false;
};
$(document).ready(function() {
$('input[name=productSearchQuery]').keyup(function() {
// submit the form
postData('POST', 'search.php', $('form[name=productSearch]').serialize(), '#productSearchResult');
});
$('a').click(function() {
postData('POST', 'add.php', $('form[name=productAdd]').serialize(), '#addResult');
});
});
</script>
UPDATE 2:
OK, first off I want to apologise for not including this code in my original post, I honestly didn't suspect it could be the cause. I've fixed my code after rolling back the JS which is returned with the radio buttons. I can't understand why the new JS causes the problem above, whereas the old JS does not.
Here's the old JS that works fine:
$('tr.product input[type=radio]').hide();
$('tr.product').mouseover(function() {
$(this).addClass('blueHover');
}).mouseout(function() {
$(this).removeClass('blueHover');
});
$('tr.product').click(function(event) {
$('tr.product').removeClass('blueChecked');
$(this).closest('tr').addClass('blueChecked');
if (event.target.type !== 'radio') {
$(':radio', this).attr('checked', true);
}
});
Here's the new JS that causes the problems above:
$('tr.product input[type=radio]').hide();
$(document).on({
mouseenter: function () {
$('td', $(this).parent()).addClass('blueHover');
},
mouseleave: function () {
$('td', $(this).parent()).removeClass('blueHover');
},
click: function (event) {
$('tr.product').removeClass('blueChecked');
$(this).closest('tr').addClass('blueChecked');
if (event.target.type !== 'radio') {
$(':radio', $(this).parent().parent()).attr('checked', false);
$(':radio', $(this).parent()).attr('checked', true);
}
}
}, 'tr.product td');
Try this instead
<script type="text/javascript">
function postData(type, url, data, targetDiv) {
$.ajax({
type: type,
url: url,
contentType: 'application/json',
data: data,
success: function(response) {
$(targetDiv).html(response);
},
error: function() {
alert('Error! Plese try again.');
}
});
return false;
};
$(document).ready(function() {
$('input[name=productSearchQuery]').keyup(function() {
// submit the form
postData('POST', 'search.php', $('form[name=productSearch]').serialize(), '#productSearchResult');
});
$('a').click(function() {
postData('POST', 'add.php', $('form[name=productAdd]').serialize(), '#addResult');
});
});
</script>
You have to use jQuery on method.
$('body').on('click', 'a', function() {
postData('POST', 'add.php', $('form[name=productAdd]').serialize(), '#addResult');
});

Categories

Resources