Disable checkboxes when another is checked - javascript

I have a MVC web app, in one section i manage the permission for users (such as decide which information the user can see/edit/add/delete ecc...).
For prevent some errors, if the checkbox in the column Admin is checked the others in the row will be disabled, because the group Admin can do everything, same thing with the Manager column, but in this case only the checkboxes on his right will be disabled.
Afeter many researches, i didn't find anything which can be useful for my case
This is my View code:
<body>
<div class="limiter">
<br />
<div class="container-table100">
<div class="wrap-table100">
<div class="table">
<table id="tablePermission">
#{
CEG_dev_labelsEntities db = new
CEG_dev_labelsEntities();
int countY = 1;
//get all groups
var groups = from g in db.Groups
orderby g.group_name
select new
{
g.group_name,
g.group_description
};
<thead>
<tr class="table100-head">
<th class="column1">Username</th>
#foreach (var item in groups)
{
<td><button>#item.group_name</button</td>
}
</tr>
</thead>
foreach (var item in db.Users)
{
<tbody id="myTable">
#{
//get all user's group
var group_list = from g in db.Groups
join ug in
db.UserGroups on g.id_group equals ug.id_group
join u in db.Users on
ug.id_user equals u.id_user
where u.username ==
item.username
select new
{
g.group_name
};
//save the single values in a list
//so all information are more accesible
List<string> group_user_list = new
List<string>();
foreach (var item_ug in group_list)
{
group_user_list.Add(item_ug.group_name);
}
<tr style="cursor:default">
<tdclass="column1">
#Html.DisplayFor(model =item.username)
</td>
#foreach (var itemG in groups)
{
//check the corresponding
//checkbox if user is a member
//of a specific group
if(group_user_list.Contains(itemG.group_name))
{
<td style="padding-left:80px"><input
type="checkbox" checked="checked"
class="chkclass" username="#item.username"
groupname="#itemG.group_name" id="#countY" /></td>
}
else
{
<td><input type="checkbox" class="chkclass"
username="#item.username"
groupname="#itemG.group_name"
id="#countY" />
</td>
}
countY++;
}
</tr>
}
</tbody>
}
}
</table>
</div>
</div>
</div>
</div>
</body>
This is the table:
Any suggestion is appreciate.
Leo.
EDIT
I have this click event on checkboxes for managing user's permissions
$(document).ready(function () {
$('.chkclass').click(function () {
var getchkid = $(this).attr('id');
var isChecked = $('#' + getchkid).is(':checked');
if ($('#' + getchkid).is(':checked') == true) {
// to be send to your call
var username = $(this).attr('username');
var groupname = $(this).attr('groupname');
//here put your call ajax to your action
$.ajax({
type: 'Post',
url: '/UserGroups/AddPermission',
dataType: 'json',
data: {
'usr': username,
'grp': groupname
},
success: function (result) {
$('#' + getchkid).prop('checked', true);
},
error: function (jqxhr, status, exception) {
alert('Exception:', exception);
}
})
}
else {
if ($('#' + getchkid).is(':checked') == false) {
// to be send to your call
var username = $(this).attr('username');
var groupname = $(this).attr('groupname');
//here put your call ajax to your action
$.ajax({
type: 'Post',
url: '/UserGroups/DeletePermission',
dataType: 'json',
data: {
'usr': username,
'grp': groupname
},
success: function (result) {
if (result.error == true) {
alert('Error, must be there at least one
admin');
$('#' + getchkid).prop('checked', true);
}
else {
$('#' + getchkid).prop('checked', false);
}
},
error: function (jqxhr, status, exception) {
alert('Exception:', exception);
}
})
}
}
});
});

Since you're doing a loop where everything is the same, you could do something like this:
https://jsfiddle.net/z2mf8314/1/
$('.chkclass').click(function () {
var getchkid = $(this).attr('id');
var isChecked = $('#' + getchkid).is(':checked');
var username = $(this).attr('username');
var groupname = $(this).attr('groupname');
(getchkid == "1" && isChecked) ? $(this).closest('tr').find('input').not('#1').prop({'disabled': true, 'checked': false }) : $(this).closest('tr').find('input').prop('disabled', false);
if (isChecked) {
// to be send to your call
//here put your call ajax to your action
}
else {
// to be send to your call
//here put your call ajax to your action
}
});

Related

Remove row from table on delete success?

I want to remove the deleted row from the table but it's not working with me. I tried the below code:
Scenario: When a user click on delete link/button, it sends a delete request and deletes data from Database so it should update the table front end view and should remove the clicked deleted row on success.
// Delete remedy which is linked with a Symptom ( Symptoms Table )
$("a.remedy-row-delete").click(function(e) {
e.preventDefault();
var remedy_id = $(this).attr('data-id');
var dataString = '&id='+remedy_id;
$.SmartMessageBox({
title: "Delete Remedy",
content: "Remedy Entry will be deleted, are you sure ?",
buttons: "[YES][NO]"
}, function (ButtonPress) {
if (ButtonPress === "YES"){
$.ajax({
type: 'POST',
data: dataString,
url: '<?php echo $this->CxHelper->Route('eb-admin-delete-linked-remedy-from-symptom') ?>',
success: function(data) {
$("#deleteMessage").show().delay(5000).fadeOut();
$(this).closest('tr').remove();
}
});
}
else {
$("a.remedy-row-delete").removeClass('alert');
}
});
});
I tried $(this).parent().closest('tr').remove(); also on success but not working.
HTML markup:
<table id="cx-records-table" class="table display table-striped table-bordered" width="100%">
<thead>
<tr>
<th>
Title
</th>
<th>
Delete
</th>
</tr>
<?php foreach($remedies as $key => $remedy){ ?>
<tr>
<td class="all"><?php echo $remedy['title']; ?><br></td>
<td><a class="cx-action remedy-row-delete" href="javascript:void(0)" data-id="{{remedy['id']}}"><i class="fa fa-trash-o"></i></a></td>
</tr>
<?php } ?>
</thead>
<tbody></tbody>
</table>
Thanks
because $(this) inside of ajax function is different than from outside you should do something like this
$("a.remedy-row-delete").click(function(e) {
e.preventDefault();
var remedy_id = $(this).attr('data-id');
var dataString = '&id='+remedy_id;
var $this = $(this) // <--- 1. Add this line
$.SmartMessageBox({
...
}, function (ButtonPress) {
if (ButtonPress === "YES"){
$.ajax({
...
success: function(data) {
...
$this.closest('tr').remove(); // <----change this and will works well
}
});
}
else {
$("a.remedy-row-delete").removeClass('alert');
}
});
});
try this
// Delete remedy which is linked with a Symptom ( Symptoms Table )
$("a.remedy-row-delete").click(function(e) {
e.preventDefault();
var remedy_id = $(this).attr('data-id');
var dataString = '&id='+remedy_id;
var self = this;
$.SmartMessageBox({
title: "Delete Remedy",
content: "Remedy Entry will be deleted, are you sure ?",
buttons: "[YES][NO]"
}, function (ButtonPress) {
if (ButtonPress === "YES"){
$.ajax({
type: 'POST',
data: dataString,
url: '<?php echo $this->CxHelper->Route('eb-admin-delete-linked-remedy-from-symptom') ?>',
success: function(data) {
$("#deleteMessage").show().delay(5000).fadeOut();
$(self).closest('tr').remove();
}
});
}
else {
$("a.remedy-row-delete").removeClass('alert');
}
});
});

unable to post id of selected dropdown to controller through knockout function

This is my Post function something like this:
function Post(data) {
var self = this;
data = data || {};
self.PostId = data.PostId;
self.Message = ko.observable(data.Message || "");
self.PostedBy = data.PostedBy || "";
self.NeighbourhoodId = data.id || "";
This is my simple function in knockout. Here at the last line u can see, data: ko.toJson(post)
self.addPost = function () {
var post = new Post();
post.Message(self.newMessage());
return $.ajax({
url: postApiUrl,
dataType: "json",
contentType: "application/json",
cache: false,
type: 'POST',
data: ko.toJSON(post)
})
.done(function (result) {
self.posts.splice(0, 0, new Post(result));
self.newMessage('');
})
.fail(function () {
error('unable to add post');
});
}
Now, along with this, i want to pass dropdown selected id something like this:
data: { id: $("#Locations").val() }
Right now, i have tried using this:
data:{post: ko.toJSON(post), id: $("#Locations").val() }
but in controller, post: ko.toJSon(post) is sending nothing however i am getting id of selected dropdown but not the message property of post parameter.
If i use this line:
data: ko.toJSON(post)
then i can get every property of post parameter but then id is null so, how to deal with this.Plzz Plzz help me out.Debugger is showing nothing useful information.My Post Controller is:
public JsonResult PostPost(Post post, int? id)
{
post.PostedBy = User.Identity.GetUserId<int>();
post.NeighbourhoodId = id;
db.Posts.Add(post);
db.SaveChanges();
var usr = db.Users.FirstOrDefault(x => x.Id == post.PostedBy);
var ret = new
{
Message = post.Message,
PostedBy = post.PostedBy,
NeighbourhoodId = post.NeighbourhoodId
};
return Json( ret,JsonRequestBehavior.AllowGet);
}
on my view page,this is the button on which click event i fired addPost function
<input type="button" data-url="/Wall/SavePost" id="btnShare" value="Share" data-bind="click: addPost">
along with this, dropdown for sending id is something like this:
#Html.DropDownList("Locations", ViewBag.NeighbourhoodId as SelectList, "Select a location")
<script type="text/javascript">
$(document).ready(function () {
$("#btnShare").click(function () {
var locationSelected = $("#Locations").val();
var url = '#Url.Action("PostPost", "Post")';
$.post(url, { id: locationSelected },
function (data) {
});
});
});
</script>
Plzz someone help me out.I am not getting what to do from here.

Script disables some components on my table

This is how my webpage looks like:
As can be seen in the picture I have I have search on the top right, in the bottom right I have the amount of pages etc..
But as I add another project here by clicking "Lägg till ny" and add a project for some reason my page will end up like this:
http://puu.sh/kKSZz/387c71f487.png
As can be seen the table "Breaks" the search field gets removed and so does the pages. Same things happens when I chose to edit or delete a project I've already added.
This is my view:
<div id="tabs-current">
<div id="ConsultantTimes">
#{
Html.RenderAction("ConsulantTimes");
}
</div>
<a href="javascript:OpenDialog()" class="btn btn-primary">
Lägg till ny
</a>
</div>
As can be seen the table is a partial view and here it is:
<table class="table table-striped table-bordered table-hover" id="sample_1">
<thead>
<tr>
<th>Projekt</th>
<th>Mitt Datum</th>
<th>%</th>
<th>Projektdatum</th>
</tr>
</thead>
<tbody>
#foreach (var project in ViewData["times"] as List<ConsultantProjectTime>)
{
<tr>
<td>
<a href="javascript:OpenDialog2('#project.ID','#project.FK_ProjectID','#project.StartDate.ToShortDateString()','#project.EndDate.ToShortDateString()','#project.Pct');">
#project.Project.ProjectName
</a>
</td>
<td>#(project.StartDate.ToShortDateString() + " - " + project.EndDate.ToShortDateString())</td>
<td>#(project.Pct)%</td>
<td>
#if (project.Project.StartDate.HasValue && project.Project.EndDate.HasValue)
{
#(project.Project.StartDate.Value.ToShortDateString() + " - " + project.Project.EndDate.Value.ToShortDateString())
}
</td>
</tr>
}
</tbody>
And this is my script I run when I choose to add another project:
$("#dialog").dialog({
bgiframe: true,
autoOpen: false,
height: 220,
width: 305,
modal: true,
buttons: {
'Spara': function() {
if (!validate()) {
alert('Procent måste vara mellan 0-100');
return false;
}
locstring = "#(Url.Action("Index"))/Update/?";
locstring += '&projectId=' + $('#projectList').val();
locstring += '&startDate=' + $('#startDate').val();
locstring += '&endDate=' + $('#endDate').val();
locstring += '&pct=' + $('#pct').val();
var sid = $('#sId').text();
if (sid != "") {
locstring += '&id=' + sid;
//locstring = "/Delete/" + sid;
}
//window.location = locstring;
$.ajax({
type: "GET",
url: locstring,
dataType: "html",
success: function(data) {
//alert(locstring);
$('#dialog').dialog('close');
ReloadTable();
}
});
},
'Avbryt': function() {
$(this).dialog('close');
},
'Ta bort': function() {
var sid = $('#sId').text();
if (sid != "") {
locstring = "#(Url.Action("Index"))/Delete/" + sid;
//locstring += '&delete=true&id=' + sid;
$.ajax({
type: "GET",
url: locstring,
dataType: "html",
success: function(data) {
$('#dialog').dialog('close');
ReloadTable();
}
});
Note, when this happends I have no errors in my console.
Found the error but not sure how to solve it, it's my ReloadTable function:
function ReloadTable() {
if (navigator.appName == "Microsoft Internet Explorer") {
//alert('suck..');
window.location.reload();
} else {
$.ajax({
type: "GET",
url: '#(Url.Action("ConsulantTimes"))',
dataType: "html",
success: function(data) {
$('#dialog').dialog('close');
$('#ConsultantTimes').html(data);
}
});
}
}
What you are doing is replacing the entire contents of #ConsultantTimes and replacing it with the data variable. Use $( "sample_1" ).replaceWith(data); instead, or maybe prepend or append.

Asp.net / JavaScript Can't remove entry from table

I'm trying to remove my entry to my table but when I press the remove button nothing happends, I know it goes into the remove method as it hits my Alert I did set there.
This is my Script to open a dialog:
function OpenDialog2(id, projectId, startDate, endDate, pct) {
ClearDialog();
$('#projectList').val(projectId);
$('#startDate').val(startDate);
$('#endDate').val(endDate);
$('#pct').val(pct);
$('#sId').text(id);
$('#dialog').dialog('open');
}
This is my method trying to remove it:
'Ta bort': function () {
alert("Ta bort");
var sid = $('#sId').text();
if (sid !== "") {
locstring = "#Url.Action("Index")/Delete/" + sid;
$.ajax({
type: "GET",
url: locstring,
dataType: "html",
success: function (data) {
$('#dialog').dialog('close');
reloadTable();
}
});
}
This is my Partial View:
#foreach (var project in ViewData["times"] as List<ConsultantProjectTime>)
{
<tr>
<td>
<a href="javascript:OpenDialog2('#project.ID','#project.FK_ProjectID','#project.StartDate.ToShortDateString()','#project.EndDate.ToShortDateString()','#project.Pct');">
#project.Project.ProjectName
</a>
</td>
<td>#(project.StartDate.ToShortDateString() + " - " + project.EndDate.ToShortDateString())</td>
<td>#(project.Pct)%</td>
<td>
#if (project.Project.StartDate.HasValue && project.Project.EndDate.HasValue)
{
#(project.Project.StartDate.Value.ToShortDateString() + " - " + project.Project.EndDate.Value.ToShortDateString())
}
</td>
</tr>
}

Group multiple AJAX success calls into one

I'm updating records in my database using a checkbox in a table. I'm trying to offer 1 Alert after ALL the updates went through, rather than alerting for each individual success call
$('#update').click(function () {
$('#view_26 tbody input[type=checkbox]:checked').each(function() {
var id = $(this).closest('tr').attr('id');
$.ajax({
url: 'https://api.knackhq.com/v1/objects/object_1/records/' + id,
type: 'PUT',
data: {field_1: 'Closed'},
success: function (response) {
alert('updated!');
}
});
Is this possible?
Count your successful calls and compare with the total number of calls.
$('#update').click(function () {
var calls=$('#view_26 tbody input[type=checkbox]:checked').length;
var success=0;
$('#view_26 tbody input[type=checkbox]:checked').each(function() {
var id = $(this).closest('tr').attr('id');
$.ajax({
url: 'https://api.knackhq.com/v1/objects/object_1/records/' + id,
type: 'PUT',
data: {field_1: 'Closed'},
success: function (response) {
success+=1;
if(success==calls) alert('updated!');
}
});
Maybe you should also catch unsuccessful calls.
Can you build and PUT the entire JSON array instead of one row at a time? This, of course, would require modifying your web service to get the record id from the JSON instead of the url. It's a better practice to limit your calls in this manner.
$('#update').click(function () {
var myJSON=[];
$('#view_26 tbody input[type=checkbox]:checked').each(function() {
var id = $(this).closest('tr').attr('id');
myJSON.push({ID:id,field_1:'Closed'});
});
//end of each
$.ajax({
url: 'https://api.knackhq.com/v1/objects/object_1/records/',
type: 'PUT',
data: myJSON,
success: function (response) {
alert('updated!');
}
});
All you need to do is to compare the length of checkboxes against the index to see if they are equal, like below.
$('#update').click(function () {
var checkboxes = $('#view_26 tbody input[type=checkbox]:checked'),
len = checkboxes.length;
checkboxes.each(function(i) {
var id = $(this).closest('tr').attr('id');
$.ajax({
url: 'https://api.knackhq.com/v1/objects/object_1/records/' + id,
type: 'PUT',
data: {field_1: 'Closed'},
success: function (response) {
if (i === len - 1 ) {
alert('updated!');
}
}
});
})
});
Try
$('#update').click(function () {
var elem = $('#view_26 tbody tr input[type=checkbox]:checked');
var res = $.map(elem, function(el, i) {
var id = $(el).closest('tr').attr('id');
console.log(id);
return $.ajax({
url: 'https://api.knackhq.com/v1/objects/object_1/records/' + id,
type: 'PUT',
data: {field_1: 'Closed'}
});
});
$.when.apply($, res)
.then(function() {
alert("updated!");
}, function(jqxhr, textStatus, errorThrown) {
alert(textStatus +" "+ jqxhr.status +" "+ errorThrown);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="update">update</button>
<table id="view_26">
<tbody>
<tr id="0">
<td>
<input type="checkbox" value="">
</td>
</tr>
<tr id="1">
<td>
<input type="checkbox" value="">
</td>
</tr>
<tr id="2">
<td>
<input type="checkbox" value="">
</td>
</tr>
</tbody>
</table>

Categories