How to select the all the rows in jquery data table - asp.net-mvc

I have two buttons in my page "Select All" and "Deselect All". I need to select the all the rows when i click the select all button and save the list of id in my variable. When Click deselect ll button it should be deselect the all rows . How will we do that?
[HttpPost]
public ActionResult Action Name(pssing value)
{
DataTable dataTable = new DataTable();
// my code
var MyModel = new List<List<string>>();
foreach (var joblist in Jobs)
{
var sublist = new List<string>();
sublist.Add(checked.false);
sublist.Add(values));
sublist.Add(values));
....etc
baseModel.Add(sublist);
}
return new DataTableResult(return);
}
Html :
<table cellpadding="0" cellspacing="0" border="0" class="display" id="AssignJobsTable" width="100%">
<thead>
<tr>
<th><input type="checkbox" id="selectall"/></th>
<th>ID</th>
etc ......
</tr>
</thead>
script:
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});
When i click the select all check box it cant bind the value form the controller.

try this
$('table#tableId> tbody > tr').addClass('highlight');
$('table#tableId> tbody > tr').removeClass('highlight')addClass('noHeilight');

sample table
<table border="1">
<tr>
<th><input type="checkbox" id="selectall"/></th>
<th>Cell phone</th>
<th>Rating</th>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="1"/></td>
<td>BlackBerry Bold 9650</td>
<td>2/5</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="case" name="case" value="2"/></td>
<td>Samsung Galaxy</td>
<td>3.5/5</td>
</tr>
</table>
sample script:
$(function(){
// add multiple select / deselect functionality
$("#selectall").click(function () {
$('.case').attr('checked', this.checked);
});
// if all checkbox are selected, check the selectall checkbox
// and viceversa
$(".case").click(function(){
if($(".case").length == $(".case:checked").length) {
$("#selectall").attr("checked", "checked");
} else {
$("#selectall").removeAttr("checked");
}
});
});

you should set id attr for checkboxes and put row id in the id attr and use the below code for selecting and deselecting:
$(document).ready(function(){
$("#selectall").click(function () {
var isSelect;
if($(this).is(":checked")) {
isSelect=true;
}else{
isSelect=false;
}
$("table tr td input[type=checkbox]").each(function(){
if(isSelect) {
$(this).prop('checked', true);
SelectedItems+=$(this).val()+":";
}else{
$(this).prop('checked', false);
SelectedItems="";
}
$("#Result").html(SelectedItems);
});
});
});

This is my approach of keeping track of all the selected rows in a datatable.
http://www.datatables.net/release-datatables/examples/plug-ins/plugin_api.html
The idea is to check the current page that the user is on and select/deselect the rows that is currently being viewed. You would loop through the page's rows and store the selected row into an array for future reference.
With this approach you would limit the time it takes to select/deselect all rows in the table.
Only show whats needed base on the view that user is seeing.
No hang up because the table is too busy checking/unchecking each row.
//stored checked box list
var result = [];
var selectAll = false;
var table5 = $('#example5').dataTable({
'fnDrawCallback':function(oSettings){
var anNodes = this.oApi._fnGetTrNodes( oSettings );
var anDisplay = $('tbody tr', oSettings.nTable);
//write your logic for pagination
//example
/*
$('tbody tr td:first-child input[type=checkbox]').on('click', function(){
if($(this).is(':checked')){
if($.inArray(....) != -1){push result}
}else{
if($.inArray(....) != -1){splice result}
}
}
if(selectAll){
for(var i = 0; i < anDisplay.length; i++){
//check if it's in result array
//add to the array
}
}else{
for(var i = 0; i < anDisplay.length; i++){
//check if it's in result array
//delete from the array
}
}
*/
}
})
That would be your logic for keeping track of the checked row.

Related

how to disabled asp-action link after one click

i would like to disabled asp=action link after one click
i have a foreach loop to display my book in table in my view
my asp-action for add book in the cart is in the loop but i want to disabled just the book who already in the cart not all books
<a asp-action="AcheterLivre" asp-Controller="Achat" asp-route-id="#item.Isbn" id="disabled" onclick="return myFunction(this);"> Ajouter
i try something with jquery but its dont work well
i tried this
<script>
function myFunction() {
$("#disabled").one("click", function () {
alert("this book is already in the cart");
});
}
i have this function in my class
its verify if the books is in the cart maybe i should use it ?
public bool IsPresent(string isbn)
{
//rechercher si l'isbn correspond a un livre de la liste
AchatLivreViewModel livre = ListeElements.Find(element => element.Isbn == isbn);
if (livre != null)
{
return true;
}
else
{
return false;
}
}
Why not trying this simple approach:
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#item.Isbn
</td>
<td>
#item.Titre
</td>
<td>
<label class="btn btn-primary" style="padding:0">Add to Cart</label>
</td>
<td>
<label class="btn btn-danger" style="padding:0">Remove From Cart</label>
</td>
</tr>
}
</tbody>
And in your javascript, if you don't want to use Ajax, you can manage your cart items all on client side using an array of objects, Let's name it CartItems:
var CartItems = [];
$('.ADD2CART').click(function () {
if ($(this).closest('tr').hasClass("ExistingInCart")) {
alert('Already in Cart !!');
}
else {
// add this item to the Cart through Ajax or
// local javascript object: e.g.:
CartItems.push({
ISBN: $(this).closest('tr').find('td:eq(0)').text().trim(),
Title: $(this).closest('tr').find('td:eq(1)').text().trim(),
});
$(this).closest('tr').addClass("ExistingInCart");
}
return false; //to prevent <a> from navigating to another address
});
$('.RemoveFromCART').click(function () {
$(this).closest('tr').removeClass("ExistingInCart");
var isbn = $(this).closest('tr').find('td:eq(0)').text().trim();
CartItems = CartItems.filter(x => x.ISBN !== isbn);
return false;
});
Once you need to submit or post the page, you have all the already selected books in CartItems array.
To add this javascript code to your view, choose one of the options:
Put this block at the bottom of your view and copy the above script inside the <script></script> tag:
#section scripts{
<script>
.... copy it here ...
</script>
}
copy the script code inside a newFile.js and add it to your view
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/newFile.js"></script>
You may decide to bundle this newFile.js
try this:
Ajouter
And your Javascript:
function foo(input) {
if ($(input).attr('yetClickable') === '1') {
$(input).attr('yetClickable', '0');
return true;
}
else {
// this false returning will counteract the effect of click event on the anchor tag
return false;
}
}
Once an Item is removed from the cart, again you need javascript to select that Item by its Id and change the yetClickable attribute back to 1 (in order to be clickable).
Note: This idea above (upon your scenario) works until the page is not reloaded. Otherwise, you need to handle ADD/Remove operations on the Cart through Ajax.
Hope this helps.

checkbox value always showing null value in mvc

I am always getting null value through checkbox in mvc. If the checkbox is checked or uncheck it contain null value only.
Here is my code,
View Page
#model IEnumerable<SchoolWebApplication.Models.EventMaster>
<table id="tblEvent" class="table" cellpadding="0" cellspacing="0">
<tr>
<th style="width:100px; display:none">Event Id</th>
<th style="width:150px">Event</th>
<th style="width:150px">Active</th>
</tr>
#if(Model != null)
{
foreach (SchoolWebApplication.Models.EventMaster eventMaster in Model)
{
<tr>
<td class="EventID" style="display:none">
<span>#eventMaster.EventID</span>
</td>
<td class="Event">
<span style="color:darkgreen">#eventMaster.Event</span>
<input type="text" value="#eventMaster.Event" style="display:none; color:darkgreen" />
</td>
<td class="IsActive">
<span style="color:darkgreen">#eventMaster.IsActive</span>
#if (#eventMaster.IsActive == true)
{
<input type="checkbox" value="#eventMaster.IsActive" style="display:none; color:darkgreen" checked="checked" name="abc"/>
}
else
{
<input type="checkbox" value="#eventMaster.IsActive" style="display:none; color:darkgreen" name="abc"/>
}
</td>
<td>
<a class="Edit" href="javascript:;">Edit</a>
<a class="Update" href="javascript:;" style="display:none">Update</a>
<a class="Cancel" href="javascript:;" style="display:none">Cancel</a>
</td>
</tr>
}
}
</table>
<script type="text/javascript">
function AppendRow(row, EventID, Event, IsActive) {
//Bind EventID.
$(".EventID", row).find("span").html(EventID);
//Bind Event.
$(".Event", row).find("span").html(Event);
$(".Event", row).find("input").val(Event);
//Bind IsActive.
$(".IsActive", row).find("span").html(IsActive);
$(".IsActive", row).find("input").val(IsActive);
$("#tblEvent").append(row);
};
//Edit event handler.
$("body").on("click", "#tblEvent .Edit", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length >= 0) {
$(this).find("input").show();
$(this).find("span").hide();
}
});
row.find(".Update").show();
row.find(".Cancel").show();
$(this).hide();
});
//Update event handler.
$("body").on("click", "#tblEvent .Update", function () {
var row = $(this).closest("tr");
$("td", row).each(function () {
if ($(this).find("input").length >= 0) {
var span = $(this).find("span");
var input = $(this).find("input");
span.html(input.val());
span.show();
input.hide();
}
});
row.find(".Edit").show();
row.find(".Cancel").hide();
$(this).hide();
var event = {};
event.EventID = row.find(".EventID").find("span").html();
event.Event = row.find(".Event").find("span").html();
event.IsActive = row.find(".IsActive").find("span").html();
$.ajax({
type: "POST",
url: "/Event/Update",
data: JSON.stringify({ eventMaster: event }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(response.IsActive);
}
});
});
</script>
Controller
try
{
EventMaster updatedEvent = (from c in entities.eventMaster
where c.EventID == eventMaster.EventID
select c).FirstOrDefault();
updatedEvent.Event = eventMaster.Event;
updatedEvent.IsActive = eventMaster.IsActive;
entities.SaveChanges();
return new EmptyResult();
}
catch (Exception ex)
{
return View();
}
Now, in table there is a three field EventID, Event and Active. In active there is a checkbox containing at update time.
Now, the issue is coming that if the checkbox is check or not check it is containing null value only.
So thats why at the fetch time it showing uncheck only.
Thank You.
Asking for the .val of a checkbox will get you the contents (if any) of the value attribute on the input element - this will not change when the user checks the box.
To check if a checkbox is checked in jQuery you should use something like:
if (input.is(":checked")){}
At the moment, you're storing the current value of .IsActive in the span and the value of the checkbox, and then when the update method runs, just grabbing that same value and putting it into the span - resulting in not updating anything.
Looking further at your code though - you should confirm what your method is actually posting back to the server - looking at it you are passing raw HTML into some parameters on the object:
event.IsActive = row.find(".IsActive").find("span").html();
At best, event.IsActive will be the string "True" (or False), rather than an actual boolean that your model is expecting. You would be better off changing that line to something like:
event.IsActive = row.find(".IsActive").find("input").is(":checked");
And then confirm what is being sent to the server in the network tab of your browser.

Copy a row between 2 jquery Datatables and then update my DB

I already have a portion of this working using Jquery-Ui, I'd appreciate some further input.
I am able to drag and drop a row from Table1 onto Table2.
issues
When I drop the new row, it does appear on table2 but table2 collapses for some reason and I have to expand it to see the new row
Table1 looks like the row was removed but if you use the Order arrow it reappears. - This issue has been fixed
Additional Question...
I wish to push this new row of data into my db via ajax call...should I try to send the data at the end of the table2.droppable function or should I use some datatbles function in table2 to realise there is new data and then fire?
<table class="dataTable" id="table1">
<thead>
<tr>
<th>Rendering engine</th>
</tr>
</thead>
<tbody>
<tr>
<td>Trident</td>
</tr>
<tr>
<td>Trident</td>
</tr>
<tr>
<td>Trident</td>
</tr>
<tr>
<td>Trident</td>
</tr>
</tbody>
</table>
<h2>Table 2</h2>
<table class="dataTable" id="table2">
<thead>
<tr>
<th>Rendering engine</th>
</tr>
</thead>
</table>
var t1 = $('#table1').DataTable();
var t2 = $('#table2').DataTable();
//this will hold reference to the tr we have dragged and its helper
var c = {};
$("#table1 tr").draggable({
helper: "clone",
start: function (event, ui) {
c.tr = this;
c.helper = ui.helper;
}
});
$("#table2").droppable({
drop: function (event, ui) {
t2.row.add(c.tr).draw();
// <-- Do this if you want to remove the rows from the first table
$(c.tr).remove();
$(c.helper).remove();
//Redraw Table1
t1.draw();
// -->
return false;
}
});
Fiddle
I would use the code as follows. This will allow you to handle any exceptions that may occur in the process of inserting data in the database.
var t1 = $('#table1').DataTable();
var t2 = $('#table2').DataTable();
//this will hold reference to the tr we have dragged and its helper
var c = {};
$("#table1 tr").draggable({
helper: "clone",
start: function (event, ui) {
c.tr = this;
c.helper = ui.helper;
}
});
$("#table2").droppable({
drop: function (event, ui) {
//Insert the data into my database.
insertData(function (success) {
if (success) {
//Move the row.
t2.row.add(c.tr).draw();
$(c.tr).remove();
$(c.helper).remove();
//Re-draw the tables.
t1.draw();
t2.draw();
}
else {
//Handle a failed insert.
alert("Unable to insert data!");
}
});
}
});
function insertData(cb) {
//Perform some AJAX.
//Test a success.
cb(true);
//Test a Failure.
//cb(false);
}

Why is the data from my html table not in the form values on a post?

I have a page/view that builds a table from a model passed in. I'm using html5 drag and drop features to allow the user to move items from one table cell to another. When I submit the form none of the data in my table is posted back to the server. The table is inside the form tag. Shouldn't the table data be sent back to the server?
The code for my view is
#model the19thTee.Core.ScheduleWeek
#{
ViewBag.Title = string.Format("Edit Schedule Week# {0} | The 19th Tee", Model.WeekNumber);
Layout = "~/Views/Shared/_the19thTeeLayout.cshtml";
}
<link href="~/styles/edit-schedule.css" rel="stylesheet" />
<h2>Edit Schedule Week - Week# #Model.WeekNumber - #Model.Date.ToShortDateString()</h2>
#using (#Html.BeginForm())
{
<p>Drag and drop foursomes and teams/players in the box below as a temporary holding area.</p>
<div id="holding-container" ondrop="drop(event)" ondragover="handleDragOver(event)"></div>
<div class="schedule_container">
<table class="schedule_table">
<tbody>
<tr>
<th colspan="2" class="schedule_table_header_cell">Date</th>
#foreach (var #foursome in #Model.Foursomes)
{
<th class="schedule_table_header_cell">#foursome.TeeTime.Time</th>
}
</tr>
<tr>
<td>#Model.WeekNumber</td>
<td>#Model.Date.ToShortDateString()</td>
#foreach (var #foursome in #Model.Foursomes)
{
<td class="foursome-cell">
<div class="foursome-container" ondrop="drop(event)" ondragover="handleDragOver(event)" ondragestart="drag(event)">
<div id="#string.Format("foursome{0}", #foursome.PositionIndex)" class="foursome" draggable="true" ondragstart="drag(event)" ondrop="drop(event)" ondragover="handleDragOver(event)">
<p>Move the whole foursome</p>
<div class="players-container" ondrop="drop(event)" ondragover="handleDragOver(event)">
<p>Drag and drop individual players from/to here</p>
#foreach (var #team in #foursome.Teams)
{
<div id="#string.Format("team{0}", #team.TeamNumber)" class="team-container" draggable="true" ondragstart="drag(event)">#team.TeamName</div>
}
</div>
</div>
</div>
</td>
}
</tr>
</tbody>
</table>
</div>
<div id="save-cancel-container"><input type="submit" class="btn btn-primary" id="submit-button" name="submit-button" value="Save" />Cancel</div>
}
<script>
function handleDragStart(e) {
this.style.opacity = '0.4'; // this / e.target is the source node.
this.style.add("dragging");
}
function handleDragOver(e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
e.dataTransfer.dropEffect = 'move'; // See the section on the DataTransfer object.
return false;
}
function handleDragEnter(e) {
// this / e.target is the current hover target.
this.classList.add('over');
}
function handleDragLeave(e) {
this.classList.remove('over'); // this / e.target is previous target element.
}
function handleDrop(e) {
e.preventDefault();
// this / e.target is current target element.
if (e.stopPropagation) {
e.stopPropagation(); // stops the browser from redirecting.
}
// See the section on the DataTransfer object.
var data = e.dataTransfer.getData("text");
e.target.appendChild(document.getElementById(data));
return false;
}
function handleDragEnd(e) {
// this/e.target is the source node.
//[].forEach.call(containers, function (container) {
// container.classList.remove('over');
//});
e.target.classList.remove("dragging");
}
//var containers = document.querySelectorAll('#foursome-container, #player-container');
//[].forEach.call(containers, function (container) {
// container.addEventListener('dragstart', handleDragStart, false);
// container.addEventListener('dragenter', handleDragEnter, false)
// container.addEventListener('dragover', handleDragOver, false);
// container.addEventListener('dragleave', handleDragLeave, false);
// container.addEventListener('drop', handleDrop, false);
// container.addEventListener('dragend', handleDragEnd, false);
//});
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
console.log("target.id = " + ev.target.id);
ev.target.classList.add("dragging");
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
console.log("data = " + data);
var isTeam = data.startsWith("team");
console.log("isTeam = " + isTeam);
var el = document.getElementById(data);
console.log(el);
console.log("drop target = " + ev.target.id);
if ((isTeam && ev.target.className == "players-container") || (!isTeam && ev.target.className == "foursome-container") || ev.target.id == "holding-container"){
ev.target.appendChild(el);
el.style.opacity = 1.0;
el.classList.remove("dragging");
console.log("clearing data");
ev.dataTransfer.clearData();
}
}
</script>

validation for either or dynamic textbox in mvc3 razor?

I have a form that form loads a partial view when i select the dropdown values.Here the partialview loads two dynamic textbox with different ID values.
#model List<DataBaseModel.OrderQuoteTBvalues>
#{
ViewBag.Title = "_ingroundDynamic";
}
#if (Model.Count() > 0)
{
<table>
<tr>
<td valign="top">
<div>
<table border="0" cellpadding="3" cellspacing="3" width="20%">
<tr style="background-color: #808080; color: #fff; font-size: 14px;">
<th align="left" width="100px">Pool Shape Type</th>
<th align="center" width="20px">Feet<br>
<th align="left" width="20px">Inch</th>
</tr>
#foreach (var item in Model)
{
<tr>
<td>#item.Shape_type</td>
<td>
<input style="width: 100px;" type="text" onkeydown="Integerkeydown(event)" id="PF:#item.Shape_type" name="PF:#item.Shape_type" /></td>
<td>
<input style="width: 100px;" type="text" onkeydown="Numerickeydown(event)" onchange="PIChange(this)" id="PI:#item.Shape_type" name="PI:#item.Shape_type" maxlength="4" /></td>
</tr>
}
}
Here the model is as follows:
public class OrderQuoteTBvalues
{
public string Shape_type { get; set; }
}
After that i have placed the next button onSubmit. if i click the Next button means i need to validate, either or textbox contains value. if it contains the value the validation true else false.
How to achieve that. Need to write any Custom Validation Method?.. If i give class="required" means all textbox is validated. but i need either or textbox to be validated.? Please help me to solve this issue. Thank you so much.
Try below Jquery
$("#validate").live({
click: function() {
var rows = $("#your_table tr:gt(0)"); // your_table is id of you table---gt(0) to skip first row
var i=true;
rows.each(function(index) {
var firsttext = $("td:nth-child(1) input", this).val();
var secondtext = $("td:nth-child(2) input", this).val();
if(firsttext=="" && secondtext=="")
i=false;
});
if(i==true)
alert('Valid');
else
alert("Invalid")
}
});
Child differ according to your order so correct that
Hope it helps leave comment if not understood
$("#btnNext").click( function() {
var valid = false;
if($("#table tr").length > 0) {
var textbox1 = $("table tr td:nth-child(1) input", this).val();
var textbox2 = $("table tr td:nth-child(2) input", this).val();
if(textbox1=="" && textbox2==""){
valid = false;
}
else if(textbox1 != "" && textbox2 != "") {
valid = false;
}
else {
valid = true;
}
}
});
the output will be like this friends.

Resources