Displaying delete icon when checkbox is selected - JS - javascript

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

Related

checkbox stored all option into database instead of one

Currently, my checkbox values is being stored as ["A","B","C"] into the database when I have only selected one option (eg C). Also, I have another question - is there any way possible to store it as ABC instead?
$(document).ready(function() {
"use strict";
var role;
});
function savenewuser() {
var url = serverURL() + "/newadmin.php";
checklist = new Array();
$('input:checkbox[name="roles[]"]').each(function() {
checklist.push($(this).val());
});
role = JSON.stringify(checklist);
$.ajax({
url: url,
type: 'GET',
data: {
"role": role,
},
success: function(arr) {
_getNewUserResult(arr);
},
error: function() {
alert("error");
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><label for="rights">Rights</label></div>
<input type="checkbox" name="roles[]" value="A">Bookings
<input type="checkbox" name="roles[]" value="B">Incident Booking
<input type="checkbox" name="roles[]" value="C">Edit User
You're saving all the checkboxes:
$('input:checkbox[name="roles[]"]').each(function() {
checklist.push($(this).val());
});
Try saving :checked ones only:
$('input:checkbox[name="roles[]"]:checked').each(function() {
checklist.push($(this).val());
});

onChange Checkbox Highlight Row

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

How to combine toggle on off with http.get

I try make toggle with bootstrap toggle and give som function http.get if toggle click on or off. But i have some trouble if on clicked it work but if off clicked it didn't work. My code like this
<input id="toggle-two" type="checkbox" data-toggle="toggle" data-width="100">
<script>
$(function() {
$('#toggle-two').bootstrapToggle({
on: 'Lock',
off: 'Unlock'
}).on('change', function() {
$.ajax({
url: 'http://localhost/web.php?tN=rlock&f12=123456789',
data: { checked: $(this).prop('checked') },
success: function() {
console.log('Lock');
}
});
}).off('change', function() {
$.ajax({
url: 'http://localhost/web.php?tN=runlock&f12=123456789',
data: { checked: $(this).prop('checked') },
success: function() {
console.log('Unlock');
}
});
});
});
</script>
i don't know how to fix it, please helpme to solve my problem
You can try something like this
<input id="toggle-two" type="checkbox" data-toggle="toggle" data-width="100">
<script>
$(function() {
$('#toggle-two').bootstrapToggle({
on: 'Lock',
off: 'Unlock'
}).on('change', function() {
var Checked_or_not = this.checked, // check if checked or unchecked
tN = Checked_or_not ? 'rlock' : 'runlock'; // if checked return 'rlock' if unchecked return 'runlock' for tN in url
$.ajax({
url: 'http://localhost/web.php?tN='+ tN +'&f12=123456789', // add tN in url
data: { checked: Checked_or_not },
success: function() {
console.log('Lock');
}
});
});
});
</script>

Ajax call on checking a checkbox

I am having a two checkboxes.Now on click of one of the checkbox I want to make an ajax call to a jsp page.That jsp page is to show a table that contains datat being fetched from database.
Now,The problem is say i have two checkboxes like :
<div class="search-inputs">
<input class="searchName" type="text" placeholder="Search Here.."></input>
<input class="searchType1" type="checkbox" name="emailNotification"><label class="searchtype1label">Email Notification</label></input>
<input class="searchType2" type="checkbox" name="SharingNotification"><label class="searchtype2label">File Sharing Notification</label></input>
<input class="searchDateFrom" type="text" placeholder="Search From"></input>
<input class="searchDateTo" type="text" placeholder="Search To"></input>
<input class="Datesubmit" type="button" value="Search"></input>
<div id="container"></div>
How to do it ?Please help
My Script part :
$(document).ready(function () {
$('.search-select').on('change', function(){
$('.search-inputs').children().hide();
var classn =$(this).find(":selected").val();
//alert(classn);
if(classn=='searchName')
{
//alert("searchname");
$('.'+"searchName").show();
}
else if(classn=='searchType')
{
//alert("searchType");
$('.'+"searchType1").show();
$('.'+"searchtype1label").show();
$('.'+"searchType2").show();
$('.'+"searchtype2label").show();
}
else if(classn=='searchDate'){
//alert("searchType");
$('.'+"searchDateFrom").show();
$('.'+"searchDateTo").show();
$('.'+"Datesubmit").show();
}
});
$('#emailNotification').on('change',function() {
//var checked = $(this).is(':checked');
if(this.checked){
//alert("in");
$.ajax({
type: "POST",
url: "searchOnType.jsp",
data: {mydata: "emailNotification"},
success: function(data) {
alert('it worked');
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});
});
But how to show the table on the same page ?
you have to change your html slightly with this--
give same class name to both check boxes.
<input class="searchType" type="checkbox" name="emailNotification" id="emailNotification"><label class="searchtype1label">Email Notification</label></input>
<input class="searchType" type="checkbox" name="SharingNotification" id="SharingNotification"><label class="searchtype2label">File Sharing Notification</label></input>
Now slightly change in jquery part--
$('.searchType').click(function() {
alert($(this).attr('id')); //-->this will alert id of checked checkbox.
if(this.checked){
$.ajax({
type: "POST",
url: 'searchOnType.jsp',
data: $(this).attr('id'), //--> send id of checked checkbox on other page
success: function(data) {
alert('it worked');
alert(data);
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});
you have to use change event for this like below:
Html:
<input class="searchType1" type="checkbox" name="emailNotification"><label class="searchtype1label">Email Notification</label></input>
<input class="searchType2" type="checkbox" name="SharingNotification"><label class="searchtype2label">File Sharing Notification</label></input>
<div id="container">
</div>
JQuery:
$('#emailNotification').on('change',function() {
if(this.checked){
$.ajax({
type: "POST",
url: "searchOnType.jsp",
data: {mydata:"emailNotification"},
success: function(data) {
alert('it worked');
$('#container').html(data);
},
error: function() {
alert('it broke');
},
complete: function() {
alert('it completed');
}
});
}
});

empty title of dialog in Jquery UI

I write this script that user check checkbox info that want to delete and click delete button it delete info with ajax. My problem is that when in first time I delete everything is fine but in second time title of dialog is empty. Why?
I do that with this code after showing dialog because my title is dynamic:
$("#ui-id-1").text(tittle);
<script src="../../Scripts/jquery-1.8.3.js"></script>
<script src="../../Scripts/jquery-ui-1.9.2.custom.js"></script>
<script>
$(function () {
$(":checkbox").change(function () {
var $this = $(this);
if ($this.is(":checked")) {
$this.closest("tr").addClass("SlectedtRow");
} else {
$this.closest("tr").removeClass("SlectedtRow");
}
})
var tittle = '';
var url = '';
$("#dialog").dialog({
autoOpen: false,
width: 400,
modal: true,
resizable: false,
buttons: [
{
text: "بلی",
click: function () {
Delete();
$(this).dialog("close");
}
},
{
text: "خیر",
click: function () {
$(this).dialog("close");
}
}
]
});
var IsActive
// Link to open the dialog
$(".insertBtn").click(function (event) {
var IsSelected = false;
var ModalText = " آیا کاربر ";
$('#userForm input:checked').each(function () {
ModalText += this.value + " - "
IsSelected = true;
});
if (IsSelected) {
document.getElementById('ErrorContent').style.display = "none";
ModalText = ModalText.slice(0, -2);
if (this.id == 'DeleteUser') {
ModalText += " حذف گردد "
tittle = 'حذف کاربر'
url = '#Url.Action("DeleteUser", "UserManagement")';
}
else if (this.id == 'InActiveUser') {
ModalText += " غیر فعال گردد "
tittle = 'تغییر فعالیت کاربر '
url = '#Url.Action("ChangeActiveStatus", "UserManagement")';
IsActive = false;
}
else if (this.id == 'ActiveUser') {
ModalText += " فعال گردد "
tittle = 'تغییر فعالیت کاربر '
url = '#Url.Action("ChangeActiveStatus", "UserManagement")';
IsActive = true;
}
$('#ModalMessgae').text(ModalText);
$("#dialog").dialog("open");
$("#ui-id-1").text(tittle);
event.preventDefault();
} })
function Delete() {
var list = [];
$('#userForm input:checked').each(function () {
list.push(this.id);
});
var parameters = {};
if (url == '#Url.Action("DeleteUser", "UserManagement")') {
parameters = JSON.stringify(list);
}
else {
parameters = JSON.stringify({ "userId": list, "ISActive": IsActive });
}
$.ajax({
url: url,
type: 'POST',
contentType: 'application/json; charset=utf-8',
dataType: "html",
traditional: true,
data: parameters,
success: function (data, textStatus, jqXHR) {
$('#updateAjax').html(data);
},
error: function (data) {
$('#updateAjax').html(data);
}
}); //end ajax
}
});
</script>
html markup
#using Common.UsersManagement.Entities;
#model IEnumerable<VwUser>
#{
Layout = "~/Views/Shared/Master.cshtml";
}
<form id="userForm">
<div id="updateAjax">
#if (string.IsNullOrWhiteSpace(ViewBag.MessageResult) == false)
{
<div class="#ViewBag.cssClass">
#Html.Label(ViewBag.MessageResult as string)
</div>
<br />
}
<table class="table" cellspacing="0">
#foreach (VwUser Item in Model)
{
<tr class="#(Item.IsActive ? "tRow" : "Disable-tRow")">
<td class="tbody">
<input type="checkbox" id="#Item.Id" name="selected" value="#Item.FullName"/></td>
<td class="tbody">#Item.FullName</td>
<td class="tbody">#Item.Post</td>
<td class="tbody">#Item.Education</td>
</tr>
}
</table>
</div>
<br />
<br />
#if (!Request.IsAjaxRequest())
{
<div class="btnContainer">
delete
<br />
<br />
</div>}
set title like below
Specifies the title of the dialog. If the value is null, the title attribute on the dialog source element will be used.
Code examples:
Initialize the dialog with the title option specified:
$( ".selector" ).dialog({ title: "Dialog Title" });
//Get or set the title option, after initialization:
// getter
var title = $( ".selector" ).dialog( "option", "title" );
// setter
$( ".selector" ).dialog( "option", "title", "Dialog Title" );
see set title in dialog box

Categories

Resources